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