Measuring text width to be drawn on Canvas ( Android )
Have you looked at android.graphics.Paint#measureText(String txt)?
Supplemental answer
There is a slight difference between the width returned by Paint.measureText
and Paint.getTextBounds
. measureText
returns a width that includes the glyph's advanceX value padding the beginning and end of the string. The Rect
width returned by getTextBounds
does not have this padding because the bounds is the Rect
that tightly wraps the text.
source
Paint paint = new Paint();
Rect bounds = new Rect();
int text_height = 0;
int text_width = 0;
paint.setTypeface(Typeface.DEFAULT);// your preference here
paint.setTextSize(25);// have this the same as your text size
String text = "Some random text";
paint.getTextBounds(text, 0, text.length(), bounds);
text_height = bounds.height();
text_width = bounds.width();