赞
踩
涉及spannableString知识
https://blog.csdn.net/chentaishan/article/details/122071754
固定的宽度,当为9时字体大,为10时字体变小。
fun setTextAutoSize(textView: TextView, text: String) { //设置textView固定宽度 val layoutParams = textView.layoutParams layoutParams.width = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 30f, textView.context.resources.displayMetrics ).toInt() //必须明确 TextView的宽度(注意:实际宽度跟所在布局有关系) textView.layoutParams = layoutParams //获取控件的可绘制的宽度,加上由于精度的偏差,取控件的比例宽度 val drawWidth = (layoutParams.width - textView.paddingLeft - textView.paddingRight) * 0.98f //获取文本内容需要的宽度 val defTextWidth: Float = textView.paint.measureText(text) val proportion = drawWidth / defTextWidth //计算 字体大小比例 val spannableString = SpannableString(text) spannableString.setSpan( RelativeSizeSpan(proportion), 0, text.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE ) textView.text = spannableString }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。