我正在尝试获取文本字符串的像素宽度,但是得到的值是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
我正在尝试获取文本字符串的像素宽度,但是得到的值是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
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);
final float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
final float scaledPx = 12 * densityMultiplier;
paint.setTextSize(scaledPx);
final float size = paint.measureText("ABCDEFGHI");
size应该是以像素为单位的宽度。