繁体   English   中英

Canvas.drawText()如何真正绘制文本?

[英]How Canvas.drawText() really draws the text?

在此方法文档中,其内容为:

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);
}

两条评论:

  1. TEXT_PADDING是我在运行时转换为像素的dp尺寸(在我的情况下为3dp)。
  2. 您可以取消注释最后一行以在画布周围绘制矩形以进行调试。

也许您可以使用以下代码段查看其是否有效:

int width = this.getMeasuredWidth()/2;
int height = this.getMeasuredHeight()/2;
textPaint.setTextAlign(Align.LEFT);
canvas.drawText(displayText, width, height, textPaint);

在我的情况下,宽度和高度是任意计算的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM