【问题标题】:Textview autofit with multiline support具有多行支持的 Textview 自动调整
【发布时间】:2012-08-25 10:23:01
【问题描述】:

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

有没有其他人进行过类似的解决方案?

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

【问题讨论】:

  • 如果您列出您尝试过的解决方案以及为什么每个解决方案都不适合您以节省大家的时间,将会很有帮助:)
  • 正如我所写,我在这个网站上尝试了至少 5 种解决方案,没有一个支持多行,使用重力并正确显示文本
  • 如果您错过了,我的建议是列出您尝试过的解决方案。
  • 我不记得我尝试过哪个。我已经尝试了至少 5 个。这是我记得我访问过的一些链接:stackoverflow.com/questions/5033012/…stackoverflow.com/questions/2596452/…

标签: android textview font-size multiline


【解决方案1】:

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

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


}

【讨论】:

  • 剩下的代码在哪里?我们应该在哪里调用这个函数? “getTextBounds”中提供的字符串是什么?
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    相关资源
    最近更新 更多