Android getTextBounds返回错误的值

Android getTextBounds返回错误的值,android,Android,我试图得到一个文本字符串的宽度(以像素为单位),我得到的值是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 边界的值为0,0,8,9。该方

我试图得到一个文本字符串的宽度(以像素为单位),我得到的值是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

边界的值为0,0,8,9。该方法采用以下参数:

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);

您可以尝试使用以下代码获取从中找到的文本的宽度(以像素为单位):


大小应该是您的宽度(以像素为单位)。

如果您只需要宽度,请尝试使用paint.measureText。这就是我发现getTextBounds有一些不准确之处时所做的。请阅读以下内容:
final float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
final float scaledPx = 12 * densityMultiplier;
paint.setTextSize(scaledPx);
final float size = paint.measureText("ABCDEFGHI");