美文网首页Android知识Android技术知识
TextView字体自动适应宽度

TextView字体自动适应宽度

作者: Tonki | 来源:发表于2016-05-19 12:03 被阅读0次

原理

布局完成后,根据当前字体大小和已绘制的宽度与TextView的宽度的比例调整字体相应的比例。
调整后字体大小 = view宽度 / 绘制宽度 * 当前字体大小

public class ScaleTextView extends TextView {
    public ScaleTextView(Context context) {
        this(context, null, 0);
    }

    public ScaleTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ScaleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Override public void onGlobalLayout() {
                //测量字符串的长度
                float measureWidth = getPaint().measureText(String.valueOf(getText()));
                //得到TextView 的宽度
                int width = getWidth() - getPaddingLeft() - getPaddingRight();
                //当前size大小
                float textSize = getTextSize();
                if (width < measureWidth) {
                    textSize = (width / measureWidth) * textSize;
                }
                //注意,使用像素大小设置
                setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }
}

相关文章

网友评论

    本文标题:TextView字体自动适应宽度

    本文链接:https://www.haomeiwen.com/subject/kllwrttx.html