自定义TextView字体自适应

/**
 * Description 字体大小跟随宽度变化
 * Author puyantao
 * Email [email protected]
 * Date 2019/6/26 16:34
 */

@SuppressLint("AppCompatCustomView")
public class AutofitTextView extends TextView {

    private Paint mTextPaint;
    private float mTextSize;

    public AutofitTextView(Context context) {
        super(context);
    }

    public AutofitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Re size the font so the specified text fits in the text box assuming the
     * text box is the specified width.
     *
     * @param text
     * @param textViewWidth
     */
    private void refitText(String text, int textViewWidth) {
        if (text == null || textViewWidth <= 0)
            return;
        mTextPaint = new Paint();
        mTextPaint.set(this.getPaint());
        int availableTextViewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
        float textWidth = mTextPaint.measureText(text);
        mTextSize = getTextSize();
        while (textWidth > availableTextViewWidth) {
            if (mTextSize == 0) return;
            mTextSize -= 1;
            mTextPaint.setTextSize(mTextSize);
            textWidth = mTextPaint.measureText(text);
        }
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        refitText(this.getText().toString(), this.getWidth());
    }
}

你可能感兴趣的:(自定义TextView字体自适应)