Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getTextBounds returning wrong values

Tags:

android

I'm trying to get the width in pixels of a text string I'm getting a value of 8, which does not make ence since that would mean each letter is 1 pixel whide. I have the following code

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 has the values of 0,0,8,9

like image 267
Ted pottel Avatar asked May 22 '26 22:05

Ted pottel


1 Answers

The method takes the following parameters:

getTextBounds(char[] text, int index, int count, Rect bounds)

And you request the width of only one character (the third parameter), not the whole string:

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

bounds.right is 8, which is the width of the letter A.

The correct call in your case would be:

String str = "ABCDEFGHI";
paint.getTextBounds(str, 0, str.length(), bounds);
like image 132
Gabriel Negut Avatar answered May 24 '26 12:05

Gabriel Negut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!