【问题标题】:Centering and Autosizing Text in Rect在 Rect 中居中和自动调整文本大小
【发布时间】:2016-08-06 19:15:16
【问题描述】:

我有一个矩形,我想在里面绘制文本。我希望文本垂直和水平居中,并且需要更改文本大小以适合矩形内的所有字符。这是我的代码:

@Override
public void drawFixedText(String text, Rect rect, Paint paint) {
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);

    int cX = rect.left;
    int cY = rect.top;

    float textSize = paint.getTextSize();
    paint.setTextSize(textSize);

    float textWidth = paint.measureText(text);

    while (textWidth > rect.width())  {
        textSize--;
        paint.setTextSize(textSize);
    }

    //if cX and cY are the origin coordinates of the your rectangle 
    //cX-(textWidth/2) = The x-coordinate of the origin of the text being drawn 
    //cY+(textSize/2) =  The y-coordinate of the origin of the text being drawn 

    canvas.drawText(text, cX-(textWidth/2), cY+(textSize/2), paint);
}

我试图结合Calculate text size according to width of text areaAndroid draw text into rectangle on center and crop it if needed的答案

但它不起作用,因为文本放置在矩形的左侧而不是矩形内部。我该如何解决这个问题?

【问题讨论】:

  • cXRect 的左侧,因此您不想从中减去一半的文本宽度。相反,您想从Rect 的水平中点减去它;即rect.centerX() - (textWidth / 2)。此外,每次更改大小后都需要测量文本宽度;也就是说,textWidth = paint.measureText(text); 也应该在循环内部,在 setTextSize() 调用之后。
  • 好的,我这样做了,它似乎将文本移到了矩形的左上角
  • 呃,不,这就是您发布的代码所在的位置。如果您按照我的建议更改 x 坐标,则文本应位于 Rect 的顶部居中。确保您的构建是最新的。也就是说,在更改后进行清理和重建。另外,我刚刚注意到您也希望它垂直居中,因此您需要对 y 坐标执行类似的操作,但如果担心的话,使用文本大小不会完全居中。
  • 啊,我发现了问题所在。我的问题是当我调用这个方法时我的文本被居中(Paint.setTextAlign(Align.CENTER))(即为什么它看起来在最左边)。所以修复后,它正确居中
  • 是的,感谢您的帮助!如果您发布带有更新代码的答案,我会接受它作为答案

标签: java android


【解决方案1】:

首先,您需要在每次设置文本大小后测量文本宽度。否则,如果文本开始时比 Rect 宽,您将陷入无限循环。

while (textWidth > rect.width())  {
    textSize--;
    paint.setTextSize(textSize);
    textWidth = paint.measureText(text);
}

然后,为了使文本水平居中,您需要从Rect 的水平中点减去一半的文本宽度,而不是从它的左边缘,这就是cX 将在您的sn-p 中。也就是说,在drawText() 调用中将cX - (textWidth / 2) 替换为rect.centerX() - (textWidth / 2)

此外,为了使文本垂直居中,我们需要对 y 坐标进行类似的操作。但是,为此使用文本大小不会给出正确的结果。我们需要测量文本的实际高度和与基线的偏移量,这可以使用Paint#getTextBounds() 方法来完成。

总而言之,这些更改会给出如下结果:

public void drawFixedText(String text, Rect rect, Paint paint) {
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.FILL);

    float textSize = paint.getTextSize();
    float textWidth = paint.measureText(text);

    while (textWidth > rect.width())  {
        textSize--;
        paint.setTextSize(textSize);
        textWidth = paint.measureText(text);
    }

    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);

    canvas.drawText(text,
                    rect.centerX() - textWidth / 2,
                    rect.centerY() - (bounds.top + bounds.bottom) / 2,
                    paint);
}

请注意,这假定了默认的Paint 实例。也就是说,任何影响文本对齐的属性都有其默认值进入此方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多