目标:在纯画布上运行的 Android >= 1.6。
假设我想编写一个函数,它将绘制一个(宽度,高度)的大红色矩形,然后在内部绘制黑色的Hello World 文字。我希望文本在矩形的视觉中心。那么让我们尝试:
void drawHelloRectangle(Canvas c, int topLeftX,
int topLeftY, int width, int height) {
Paint mPaint = new Paint();
// height of 'Hello World'; height*0.7 looks good
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;
看起来大致上可以工作,但肯定有更好的方法。