6

I'm using the Canvas.drawText() to write text on a custom view. I want to add a background 9-patch drawable behind the text, so I need to know the boundaries of the text drawn. The text is given by the user, so it's not a fixed size.

For now I'm using a monospace font and I managed to build a size which looks not so bad, but in the hand i'd rather use another font.

XGouchet
  • 10,002
  • 10
  • 48
  • 83

3 Answers3

9

You can use public void getTextBounds(String text, int start, int end, Rect bounds) method of Paint to get a rectangle that encloses all your text. Take a look at getTextBounds.

Hope this helps!

Vinod Maurya
  • 4,167
  • 11
  • 50
  • 81
1

You also may use measureText

mTextTimeColorPaint.measureText(timeText)

Like in this post Center Text on Watch

Community
  • 1
  • 1
Gabriel Pereira
  • 580
  • 5
  • 9
1

I think getTextBounds(String text, int start, int end, Rect bounds) can do it for you.

This method belongs to Paint class:

Refer to this link

halfer
  • 19,824
  • 17
  • 99
  • 186
N-JOY
  • 10,344
  • 7
  • 51
  • 69