第12回 メニュー画面の文字入れ(タイトル文字)
タイトル文字を入れました。
2行のタイトルですが、センター上部に入れる文字ということで、共通の処理を行うために関数を作って呼ぶようにしています。
上下の位置調整は、呼び出す側の引数のcenterで行うようにしました。
これだと、swiftでは左上が起点なので、高さの半分を引けばいいし、Androidでは左下起点なので高さの半分を足せばいいということになります。もっといい方法があるかもしれませんが。
override func draw(_ rect: CGRect) { // // 省略 // // タイトル文字 centerString(string: "ラップタイム記録アプリ", charSize: viewWidth * 0.05, center: CGPoint(x: viewWidth/2, y: viewHeight * 0.1)) centerString(string: "Recordable Lap Timer", charSize: viewWidth * 0.04, center: CGPoint(x: viewWidth/2, y: viewHeight * 0.15))// } func centerString(string: String, charSize: CGFloat, center: CGPoint) { // 文字列、文字サイズ、中央を示す座標、 let stringAttributes: [NSAttributedStringKey : Any] = [ NSAttributedStringKey.foregroundColor : UIColor.black, NSAttributedStringKey.font : UIFont.systemFont(ofSize: charSize) ] let nsstr = string as NSString // サイズを取得 let textSize: CGSize = nsstr.size(withAttributes: stringAttributes) let textTopLeft = CGPoint(x: center.x - textSize.width/2, y: center.y - textSize.height/2) // 文字列の描画 nsstr.draw(in: CGRect(origin: textTopLeft, size: textSize), withAttributes: stringAttributes) }
続いて java で書いたものです。
paint.setTextAlign(Paint.Align.CENTER);を使っているので、少しシンプルです。
@Override protected void onDraw(Canvas canvas) { // 省略 // タイトル文字 centerString("ラップタイム記録アプリ", width * 5 / 100, width/2, height*10/100, canvas ); centerString("Recordable Lap Timer", width * 4 / 100, width/2, height*15/100, canvas ); } void centerString(String string, int charSize, int x,int y, Canvas canvas) { // 文字列、文字サイズ、中央を示す座標、 // android では Paintクラスを使って色やスタイルを決めていく final Paint paint = new Paint(); // 色の指定 paint.setColor(Color.BLACK); // 文字サイズ,配置の指定 paint.setTextSize(charSize); paint.setTextAlign(Paint.Align.CENTER); // 文字列の描画 canvas.drawText(string, x, y + charSize/2 ,paint); }
で、結果がこちら。
メニュー画面がほぼできたので、ここで中断し、各メニューを作っていきます。
次は画面遷移です。私流の画面遷移、ご期待くださいませ。