我已经找到了根据文本大小自动调整textView字体的解决方案,并且找到了许多,但没有一个支持多行并且正确执行(没有截断文本并且还尊重重力值)。
有没有其他人这样做过?
是否也可以设置如何找到最佳行数的约束?也许根据最大字体大小或每行最大字符数?
答案 0 :(得分:3)
以下对我来说,恕我直言,比使用基于ellipsize的解决方案更好。
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)));
}
答案 1 :(得分:0)