DynamicFontTextView

2019-03-08  本文已影响0人  s_h_soong
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)
   }
}
上一篇下一篇

猜你喜欢

热点阅读