java - 矩形中文本的居中和自动调整大小

标签 java android

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

@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 area 的答案和 Android draw text into rectangle on center and crop it if needed

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

最佳答案

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

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

然后,为了使文本水平居中,您需要从 Rect 的水平中点减去文本宽度的一半,而不是从其左边缘(这就是代码段中的 cX)。也就是说,在 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 实例。也就是说,任何影响文本对齐的属性都有其默认值进入此方法。

关于java - 矩形中文本的居中和自动调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38807886/

相关文章:

Java-创建瓦片 map gif

java - Websphere 8.5.0.2 抛出不兼容的 java 版本

android - EditText框高度问题android

android - 滚动到表单元素

java - 如何自定义 Joda Time 日期格式的数字格式?

java - Spring abac 数据过滤与 Spring @PostFilter

java - Activity onCreate 上出现 NullPointerException

java - 位图不适用于 ListView

java - 在 JSF 中将 inputText 映射到 Date 对象

android - VOIP 应用程序(如 Marshmallow 上的 Whatsapp/Viber/Line/Skype)在锁定屏幕上的来电