package com.xty.common.weight

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.style.ImageSpan
import androidx.annotation.NonNull

/**
 * 自定义ImageSpan实现图片居中
 * 用原生的ImageSpan，图片是不能和文字居中的，要么偏上，要么偏下。
 */
class CenterImageSpan(@NonNull drawable: Drawable?) : ImageSpan(drawable!!) {

    override fun draw( @NonNull canvas: Canvas, text: CharSequence?,
        start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int,
        @NonNull paint: Paint ) {

        val b: Drawable = drawable
        val fm: Paint.FontMetricsInt = paint.fontMetricsInt
        val transY: Float = ((y + fm.descent + y + fm.ascent) / 2 - b.bounds.bottom / 2).toFloat()
        canvas.save()
        canvas.translate(x, transY)
        b.draw(canvas)
        canvas.restore()

    }

}