I am looking for method in Android that will take a input (text, text_font_size, device_width) and based on these calculations it will return how much height will required t
Paint.getTextBounds()
returns not what you would expect. Details are here.
Instead, you can try this way:
int mMeasuredHeight = (new StaticLayout(mMeasuredText, mPaint, targetWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true)).getHeight();
I've got a easier method to know the real height of a line before be painted, I don't know if this help you guys, but my solution to get the height of a line it's independent of the height of the layout, just take the font metrics like this:
myTextView.getPaint().getFontMetrics().bottom - myTextView.getPaint().getFontMetrics().top)
with that we get the real height that the fonts will take from the textview to be painted. This not give you an int, but you can make a Math.round to get a near value.
public static int getHeight(Context context, String text, int textSize, int deviceWidth) {
TextView textView = new TextView(context);
textView.setText(text);
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.AT_MOST);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
textView.measure(widthMeasureSpec, heightMeasureSpec);
return textView.getMeasuredHeight();
}
If textSize
is not given in pixels, change the first paramter of setTextSize()
.