getTextBounds返回错误的值

Ted*_*tel 2 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
Run Code Online (Sandbox Code Playgroud)

bounds的值为0,0,8,9

Gab*_*gut 5

该方法采用以下参数:

getTextBounds(char[] text, int index, int count, Rect bounds)
Run Code Online (Sandbox Code Playgroud)

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

paint.getTextBounds("ABCDEFGHI", 0, 1, bounds);
Run Code Online (Sandbox Code Playgroud)

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

在您的情况下正确的电话将是:

String str = "ABCDEFGHI";
paint.getTextBounds(str, 0, str.length(), bounds);
Run Code Online (Sandbox Code Playgroud)