我一直在寻找根据其大小自动调整 textView 字体的解决方案,并找到了很多解决方案,但没有一个支持多行并且正确执行(不截断文本并尊重重力值)。
有没有其他人进行过这样的解决方案?
是否也可以设置如何找到最佳行数的约束?也许根据最大字体大小或每行最大字符数?
最佳答案
以下对我来说比使用基于椭圆大小的解决方案更好,恕我直言。
void adjustTextScale(TextView t, float max, float providedWidth, float providedHeight) {
// sometimes width and height are undefined (0 here), so if something was provided, take it ;-)
if (providedWidth == 0f)
providedWidth = ((float) (t.getWidth()-t.getPaddingLeft()-t.getPaddingRight()));
if (providedHeight == 0f)
providedHeight = ((float) (t.getHeight()-t.getPaddingTop()-t.getPaddingLeft()));
float pix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
String[] lines = t.getText().toString().split("\\r?\\n");
// ask paint for the bounding rect if it were to draw the text at current size
Paint p = new Paint();
p.setTextScaleX(1.0f);
p.setTextSize(t.getTextSize());
Rect bounds = new Rect();
float usedWidth = 0f;
// determine how much to scale the width to fit the view
for (int i =0;i<lines.length;i++){
p.getTextBounds(lines[i], 0, lines[i].length(), bounds);
usedWidth = Math.max(usedWidth,(bounds.right - bounds.left)*pix);
}
// same for height, sometimes the calculated height is to less, so use §µ{ instead
p.getTextBounds("§µ{", 0, 3, bounds);
float usedHeight = (bounds.bottom - bounds.top)*pix*lines.length;
float scaleX = providedWidth / usedWidth;
float scaleY = providedHeight / usedHeight;
t.setTextSize(TypedValue.COMPLEX_UNIT_PX,t.getTextSize()*Math.min(max,Math.min(scaleX,scaleY)));
}
关于android - 具有多行支持的 Textview 自动调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12201132/