在Rect中居中和自动调整文本

时间:2016-08-06 19:15:17

标签: 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 areaAndroid draw text into rectangle on center and crop it if needed

的答案结合起来

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

1 个答案:

答案 0 :(得分:0)

首先,您需要在每次设置其大小后测量文本宽度。否则,如果文本的开头宽度超过Rect,则最终会出现无限循环。

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

然后,要使文本水平居中,您需要从Rect的水平中点减去文本宽度的一半,而不是从其左边缘减去,这就是cX中的cX - (textWidth / 2)。片段。也就是说,将rect.centerX() - (textWidth / 2)替换为drawText()来电中的Paint#getTextBounds()

此外,要使文本垂直居中,我们需要使用y坐标做类似的事情。但是,使用文本大小不会给出正确的结果。我们需要测量文本的实际高度和偏离基线,我们可以使用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

请注意,这假定为默认的{{1}}实例。也就是说,影响文本对齐的任何属性都将使用默认值进入此方法。

相关问题