Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string width on Android?

I would like to get height too if possible.

like image 324
Mikael Lindlöf Avatar asked Sep 02 '10 18:09

Mikael Lindlöf


People also ask

How do you find the width of a string?

var ww = string_width(str_Name + " "); draw_text(32, 32, str_Name)); draw_text(32 + ww, 32, "has won the game!"); The above code will get the width of the given string and then draw two lines of text, using the returned string width as a separator.


3 Answers

You can use the getTextBounds(String text, int start, int end, Rect bounds) method of a Paint object. You can either use the paint object supplied by a TextView or build one yourself with your desired text appearance.

Using a Textview you Can do the following:

Rect bounds = new Rect(); Paint textPaint = textView.getPaint(); textPaint.getTextBounds(text, 0, text.length(), bounds); int height = bounds.height(); int width = bounds.width(); 
like image 54
Frank Avatar answered Sep 23 '22 03:09

Frank


If you just need the width you can use:

float width = paint.measureText(string);

http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String)

like image 35
SharkAlley Avatar answered Sep 23 '22 03:09

SharkAlley


There are two different width measures for a text. One is the number of pixels which has been drawn in the width, the other is the number of 'pixels' the cursor should be advanced after drawing the text.

paint.measureText and paint.getTextWidths returns the number of pixels (in float) which the cursor should be advanced after drawing the given string. For the number of pixels painted use paint.getTextBounds as mentioned in other answer. I believe this is called the 'Advance' of the font.

For some fonts these two measurements differ (alot), for instance the font Black Chancery have letters which extend past the other letters (overlapping) - see the capital 'L'. Use paint.getTextBounds as mentioned in other answer to get pixels painted.

like image 24
arberg Avatar answered Sep 21 '22 03:09

arberg