AndroidではPaintでテキストを中心に描画

549 ワード

テキストを垂直に中央に配置するには、canvasのdrawText(text,x,y,paint)メソッドを使用します.3番目のパラメータyはbaselineの値である必要があります.計算式は次のとおりです.
int baseline = (getMeasuredHeight() - (paint.descent() - paint.ascent())) / 2 - paint.ascent();

ascentとdescentから描画境界の上下の2つの境界までの距離が一致するとしても、この距離にascent()の絶対値、すなわち-paintを加える.ascent()はbaselineの値です.
水平方向を中央にすると、上記drawTextメソッドのxの値は次のように設定できます.
int x = (getMeasuredWidth() - textWidth) / 2;
ここでtextWidthは描画テキストの幅であり、
int textWidth = (int) paint.measureText(text);
で計算されます.