目标:纯 Canvas 上的 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;
似乎或多或少可以工作,但必须有更好的方法。