如何垂直对齐文本?
- 论坛
- 如何垂直对齐文本?
8 浏览
如何垂直对齐文本?
目标:在纯画布上绘制 Android >= 1.6。
假设我想要编写一个函数,它将绘制一个(宽度,高度)为红色的矩形,然后在内部绘制一个黑色的“Hello World”文本。我希望文本在矩形的视觉中心。因此,让我们尝试一下:
void drawHelloRectangle(Canvas c, int topLeftX, int topLeftY, int width, int height) { Paint mPaint = new Paint(); // 'Hello World' 的高度;height*0.7 看起来不错 int fontHeight = (int)(height*0.7); mPaint.setColor(COLOR_RED); mPaint.setStyle(Style.FILL); c.drawRect( topLeftX, topLeftY, topLeftX+width, topLeftY+height, mPaint); mPaint.setTextSize(fontHeight); mPaint.setColor(COLOR_BLACK); mPaint.setTextAlign(Align.CENTER); c.drawText( "Hello World", topLeftX+width/2, ????, mPaint); }
现在我不知道在 drawText 的参数中标记为 ????
的内容,即我不知道如何垂直对齐文本。
类似于
???? = topLeftY + height/2 +
fontHeight/2 - fontHeight/8;
看起来基本可以,但肯定有更好的方法。