How to calculate font size for TextView
to fit in bounds defined by me with multiline text?
I have a TextView
inside a RelativeLayout
. At runtime will be known the screen size for App, based on that.
Rect boundsTv = TextPositions.getTextViewBounds(1, mainActivity.mWidthPx, mainActivity.mHeightPx);
Log.e("SlideLoader", "paint.boundsTv() left, right, top, bottom :"+boundsTv.flattenToString());//paint.boundsTv() left, right, top, bottom :163 363 1767 749
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tvText.getLayoutParams();
params.width = boundsTv.width();// right - left;
params.height = boundsTv.height();// bottom - top;
params.leftMargin = boundsTv.left; // Your X coordinate
params.topMargin = boundsTv.top; // Your Y coordinate
tvText.setLayoutParams(params);
tvText.invalidate();
And here it comes the problem. On some devices the font is to small and it fills less than the half of the TextView on other devices is so big as doesn't fit not even the half.
The output code is from a device, where the font size to big by far. I have checked a few methods, probably will suggest those 2 methods, both fail:
// left, top - right, bottom
TextPaint paint = tvText.getPaint();
paint.getTextBounds(text, 0, text.length()-1, boundsTv);
Log.e("SlideLoader", "paint.getTextBounds() left, right, top, bottom :"+boundsTv.flattenToString());//paint.getTextBounds() left, right, top, bottom :2 -33 16049 9, how to interpret this values?!
float width = paint.measureText(text);// for single line