根据文本区域的宽度计算文本大小 [英] Calculate text size according to width of text area

查看:22
本文介绍了根据文本区域的宽度计算文本大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本应该设置为具有指定宽度的 TextView.它需要计算文本大小以适应 TextView.

I have a text that should be set to TextView with specified width. It needs to calculate the text size to fit it into TextView.

换句话说:有没有办法将文本放入 TextView 区域,如 ImageView 缩放类型功能?

In other words: Is there a way to fit text into TextView area, like the ImageView scale type feature?

推荐答案

这应该是一个简单的解决方案:

This should be a simple solution:

public void correctWidth(TextView textView, int desiredWidth)
{
    Paint paint = new Paint();
    Rect bounds = new Rect();

    paint.setTypeface(textView.getTypeface());
    float textSize = textView.getTextSize();
    paint.setTextSize(textSize);
    String text = textView.getText().toString();
    paint.getTextBounds(text, 0, text.length(), bounds);

    while (bounds.width() > desiredWidth)
    {
        textSize--;
        paint.setTextSize(textSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
    }

    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}

这篇关于根据文本区域的宽度计算文本大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆