如何计算字体大小TextView
以适应我用多行文本定义的范围?
我有一个TextView
里面的RelativeLayout
。基于此,在运行时将知道 App 的屏幕尺寸。
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();
问题来了。在某些设备上,字体很小,并且它填充的文本视图不到一半,而其他设备上的字体太大,甚至不到一半。
输出代码来自一个设备,其中的字体大小要大得多。我检查了一些方法,可能会建议这两种方法,但都失败了:
// 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