在此方法文档中写道:
x The x-coordinate of origin for where to draw the text
y The y-coordinate of origin for where to draw the text
但它没有说明此文本的绘制方向。我知道文本是从原点向上绘制的,但是当我给出以下参数时,我的文本被剪切了:
canvas.drawText(displayText, 0, canvas.getHeight(), textPaint);
此外,假设我使用的是 Align.LEFT(意味着文本绘制在 x,y 原点的右侧)
那么正确的参数应该是什么(假设我不想使用固定数字)?
最佳答案
这是我最终使用的:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (textAlignment == Align.CENTER) {
canvas.drawText(displayText, canvas.getWidth()/2, canvas.getHeight()-TEXT_PADDING, textPaint);
}
else if (textAlignment == Align.RIGHT) {
canvas.drawText(displayText, canvas.getWidth()-TEXT_PADDING, canvas.getHeight()-TEXT_PADDING, textPaint);
}
else if (textAlignment == Align.LEFT) {
canvas.drawText(displayText, TEXT_PADDING, canvas.getHeight()-TEXT_PADDING, textPaint);
}
//canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), p);
}
两条评论:
- TEXT_PADDING 是我在运行时转换为像素的 dp 维度(在我的例子中是 3dp)。
- 您可以取消注释最后一行以在 Canvas 周围绘制矩形以进行调试。
关于android - Canvas.drawText() 是如何真正绘制文本的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15132134/