TextView with adaptive text size

Android8.0 and above

  • You can add autoSizeTextType to TextView to achieve

Below Android8.0

  • Can only be customized
public class PZHelp_TextView_AutoTextSize extends androidx.appcompat.widget.AppCompatTextView {
    
    
    public static final String TAG = "AutoTextSize";
    //控件的宽
    private int mViewWidth, mViewHeight;
    //计算出的文字大小
    private float sizeOfWidth, sizeOfHeight;
    //可以设置的最小文字
    private float mMinTextSize = 10;

    public PZHelp_TextView_AutoTextSize(Context context) {
    
    
        super(context);
        init();
    }

    public PZHelp_TextView_AutoTextSize(Context context, @Nullable AttributeSet attrs) {
    
    
        super(context, attrs);
        init();
    }

    public PZHelp_TextView_AutoTextSize(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    
    
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化
     */
    void init() {
    
    
        setGravity(Gravity.CENTER);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    
    
        super.onDraw(canvas);
        changeTextSize();
    }

    /**
     * 改变文字大小
     */
    private void changeTextSize() {
    
    
        TextPaint mTextPaint = getPaint();
        //获取当前文字的大小
        float mCurrentTextSize = getTextSize();
        sizeOfWidth = sizeOfHeight = mCurrentTextSize;
        //获取文字内容
        String mCurrentText = getText().toString().trim();
        //测量文字内容的长度与高度
        float mCurrentTextWidth = mTextPaint.measureText(mCurrentText);
        float mCurrentTextHeight = Math.abs(mTextPaint.descent()) + Math.abs(mTextPaint.ascent());
        if (mCurrentTextWidth > mViewWidth || mCurrentTextWidth < mViewWidth * 0.8) {
    
    //0.8是为了防止频繁计算
            //计算文字长度与文字大小的比例
            float scale = mCurrentTextWidth / mCurrentTextSize;
            //根据控件长度计算合适的文字大小
            sizeOfWidth = (float) ((mViewWidth * 0.8) / scale);
        }
        if (mCurrentTextHeight > mViewHeight || mCurrentTextHeight < mViewHeight * 0.8) {
    
    
            //计算文字高度与文字大小的比例
            float scale = mCurrentTextHeight / mCurrentTextSize;
            //根据控件高度计算合适的文字大小
            sizeOfHeight = mViewHeight / scale;
        }

        //取最合适的文字大小
        float newTextSize = Math.min(sizeOfWidth, sizeOfHeight);
        if (newTextSize < mMinTextSize) {
    
    
            newTextSize = mMinTextSize;
        }

        //重新设置文字尺寸
        setTextSize(TypedValue.COMPLEX_UNIT_PX, newTextSize);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
    
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //计算控件的宽度(如果设置了padding值,需要减去左右的padding值)
        mViewWidth = MeasureSpec.getSize(widthMeasureSpec);
        mViewHeight = MeasureSpec.getSize(heightMeasureSpec);
    }
}

Guess you like

Origin blog.csdn.net/qq_36881363/article/details/105554280