Android(安卓)自定义TextView实现文本内容自动调整字体大小以适应TextView的大小
16lz
2021-01-24
/** * 自定义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);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);refitText(this.getText().toString(), this.getWidth());}}
更多相关文章
- TextToSpeech 文本自动朗读
- Android(安卓)JSON数据与实体类之间的相互转化-------GSON实现
- android奇怪问题收集
- Android(安卓)实时视频采集—Cameara预览采集
- Android下Xml解析技术(四)、pull生成Xml文件
- android 【MeasureSpec】 introduction
- Android通过Movie展示Gif格式图片
- Android(安卓)实现生成二维码
- Android之WebView与原生js之间的相互调用