Android 自定义TextView实现文本内容自动调整字体大小以适应TextView的大小
最近做通讯录小屏机 联系人姓名显示--长度超过边界字体变小
/** * 自定义TextView,文本内容自动调整字体大小以适应TextView的大小 * @author yzp */ 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 textWidth */ 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[] charsWidthArr = new float[text.length()]; Rect boundsRect = new Rect(); mTextPaint.getTextBounds(text, 0, text.length(), boundsRect); int textWidth = boundsRect.width(); mTextSize = getTextSize(); while (textWidth > availableTextViewWidth) { mTextSize -= 1; mTextPaint.setTextSize(mTextSize); textWidth = mTextPaint.getTextWidths(text, charsWidthArr); } this.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); refitText(this.getText().toString(), this.getWidth()); } }
相关推荐
zhanghao 2020-06-16
tichangde 2020-05-19
xsgnzb 2020-03-09
lixiaotao 2020-03-02
bertzhang 2019-12-25
RexLeee 2019-12-23
MaureenChen 2019-12-03
wangjie 2019-11-10
谢恩铭 2016-01-10
时间猎人 2019-09-06
Jolestar 2016-06-02
gigipop 2019-07-01
标题 2019-07-01
jianqi 2019-07-01
RLanffy 2019-07-01
VVVinegar 2019-07-01
GeolageWu 2019-06-30
CoderChang 2019-06-30