class DynamicFontTextView : TextView {
constructor(context: Context) :super(context)
constructor(context: Context, attrs: AttributeSet) :super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) :super(context, attrs, defStyleAttr)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
adapterText(this.text.toString())
}
private fun adapterText(text: String) {
if (text.isEmpty()) {
return
}
var mTextSize =textSize
val mPaint = Paint()
mPaint.set(paint)
var drawableWidth =0
val drawableCompound =compoundDrawables
for (iin 0 until drawableCompound.size) {
if (drawableCompound[i] !=null) {
drawableWidth += drawableCompound[i].bounds.width()
}
}
val maybeWidth =width -paddingLeft - drawableWidth -
paddingRight -compoundDrawablePadding
var textWidth = mPaint.measureText(text)
while (textWidth > maybeWidth) {
mPaint.textSize = --mTextSize
textWidth = mPaint.measureText(text)
}
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize)
}
}
网友评论