表示文字列の幅

出典: YKAwiki

目次

概要

文字列をGraphics#drawString()などで描画する際、美しさの観点から文字列の幅というのはどうにも気になります。 そこで、指定文字列全体の幅を得る方法を記します。

方法

フォントインスタンスの用意

フォントクラスから新しくインスタンスを作る手もありますが面倒です。

Graphics#getFont()で現在のフォントを利用しましょう

Font nowFont = g.getFont();

テキストレイアウトの取得

フォントのインスタンス自体からは文字列の幅などが得られない(多分。)ので、テキストレイアウトを取得することにします。

TextLayout layout = new TextLayout([表示したい文字列],nowFont,
    new FontRenderContext(new AffineTransform(),false,false))

適当に。

幅の取得

TextLayout#getBounds()で大きさが得られます。Rectangle2Dなので横幅をゲット。 同様にして縦の大きさも得られます。

int strWidth = (int)laout.getBounds().getWidth();

ここで注意なのが、文字1個のサイズではなく、文字列全体のサイズが得られています。

サンプル

フォントを変更しつつ中心に表示するサンプル

public void paint( Graphics g){
 //フォント取得
 Font useFont = g.getFont();
 //新しいフォント作成
 int fontSize = 90;
 //フォントスタイル変更して新規作成
 Font newFont = useFont.deriveFont( Font.BOLD,fontSize);
 //文字列
 String msg = "ほげぴようお~ず";
 //テキストレイアウト情報取得
 TextLayout layout = new TextLayout(msg,newFont,
    new FontRenderContext(new AffineTransform(),false,false));
 //幅取得
 int strWidth = (int)layout.getBounds().getWidth();
 //タイトル表示
 int x = getWidth()/2-strWidth/2;
 int y = 100;
 g.drawString(msg,x,y);
}
表示例
拡大
表示例

関連

・ブログ記事: