android - 具有多行支持的 Textview 自动调整

标签 android textview font-size multiline

我一直在寻找根据其大小自动调整 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/

相关文章:

java - 如何绘制线条并删除我在 ImageView Android Xamarin 上绘制的线条

java - 在 Java 中重用具有常量后缀的字符串的最佳实践

android - 使用 setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom) 在 textView 的 drawable 上获取 onclick 事件

jQuery CSS 字体大小不起作用

twitter-bootstrap - Bootstrap 排版和字体大小不会改变

android - 删除 AppBarLayout 小部件 android 下方的阴影

android - ListView 可点击 false 不起作用

java - 防止 Textview android 中的负数 - 代码

android - 使用 span 在 textview 中插入标签

javascript - 单击按钮时将字体大小增加或减少 1em