3

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

Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • give a try to paint.measureText if you only need the width. That's what I do since I found getTextBounds had some inaccuracies. – Wildcopper Aug 14 '14 at 13:58
  • Read this: http://stackoverflow.com/questions/7549182/android-paint-measuretext-vs-gettextbounds – Maxim Aug 14 '14 at 14:02

2 Answers2

7

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);
Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
-1

You can try using the following code to get the width (in pixels) for your text (found from 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 should be your width in pixels.

Community
  • 1
  • 1
Mark N
  • 326
  • 2
  • 13