getTextBounds返回错误的值

3

我正在尝试获取文本字符串的像素宽度,但是得到的值是8,这不合理,因为这意味着每个字母只有1个像素宽。以下是我的代码:

Rect bounds = new Rect();
Paint paint = new Paint();
paint.setTextSize(12);
paint.getTextBounds("ABCDEFGHI", 0, 1, bounds);
width=bounds.right;      // this value is 8

bounds的值为0,0,8,9


如果你只需要宽度,可以试试paint.measureText。自从我发现getTextBounds有一些不准确之处以后,我就一直这么做了。 - Wildcopper
阅读此内容:https://dev59.com/5msz5IYBdhLWcg3w9soQ - Maxim
2个回答

7
该方法接受以下参数:
getTextBounds(char[] text, int index, int count, Rect bounds)

您只需请求一个字符的宽度(第三个参数),而不是整个字符串的宽度:

paint.getTextBounds("ABCDEFGHI", 0, 1, bounds);

bounds.right 是 8,它是字母 A 的宽度。

在您的情况下,正确的调用应该是:

String str = "ABCDEFGHI";
paint.getTextBounds(str, 0, str.length(), bounds);

-1
你可以尝试使用以下代码来获取文本的宽度(以像素为单位)(参考自Android:measureText() Return Pixels Based on Scaled Pixels):
final float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
final float scaledPx = 12 * densityMultiplier;
paint.setTextSize(scaledPx);
final float size = paint.measureText("ABCDEFGHI");

size应该是以像素为单位的宽度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接