美文网首页
自定义TextView字体自适应

自定义TextView字体自适应

作者: 涛涛123759 | 来源:发表于2019-07-01 15:05 被阅读0次
    /**
     * Description 字体大小跟随宽度变化
     * Author puyantao
     * Email 1067899750@qq.com
     * 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字体自适应

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