Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the size of a text when using Canvas.drawText()

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.

like image 483
XGouchet Avatar asked Feb 24 '11 07:02

XGouchet


2 Answers

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!

like image 138
Vinod Maurya Avatar answered Sep 22 '22 12:09

Vinod Maurya


You also may use measureText

mTextTimeColorPaint.measureText(timeText)

Like in this post Center Text on Watch

like image 36
Gabriel Pereira Avatar answered Sep 22 '22 12:09

Gabriel Pereira