Android Canvas.drawText()如何真正绘制文本?
本方法文档中写道:Android Canvas.drawText()如何真正绘制文本?,android,android-canvas,android-custom-view,Android,Android Canvas,Android Custom View,本方法文档中写道: 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); 此外,假设我
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原点的右侧)
那么正确的参数应该是什么(假设我不想使用固定数字)?也许您可以使用以下代码片段来查看它是否工作:
int width = this.getMeasuredWidth()/2;
int height = this.getMeasuredHeight()/2;
textPaint.setTextAlign(Align.LEFT);
canvas.drawText(displayText, width, height, textPaint);
在我的例子中,宽度和高度是任意计算的。这就是我最终使用的:
@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);
}
两点意见:
也许这就是你想要的(检查答案上的评论)。文本是如何剪切的?是否有文本显示?如果尝试将y值设置为画布。GeTeAuthe(2),它是否正确显示中间出现的文本?此外,您应该更具体地说出您想要完成的内容。getHeight/2也会导致文本被剪切,这一次文本的上半部分被剪切,而不是原始情况下文本的下半部分。