1

我已经寻找了根据 textView 的大小自动调整字体的解决方案,并发现了很多,但没有一个支持多行并且正确执行(不截断文本并且也尊重重力值)。

有没有其他人进行过这样的解决方案?

是否也可以设置如何找到最佳行数的约束?也许根据最大字体大小或每行最大字符数?

4

2 回答 2

3

以下对我有用,恕我直言,比使用基于椭圆的解决方案更好。

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)));


}
于 2012-10-18T09:10:48.503 回答
0

后来我问了一个类似的问题并得到了这个问题的答案:

https://stackoverflow.com/a/17786051/878126

对于自定义行为,需要相应地更改代码。

于 2013-09-14T20:27:44.143 回答