import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.text.style.ReplacementSpan
import com.banbantv.show.utils.device.DisplayUtil
import kotlin.math.abs
/**
* @Author: qqyang
* @Date: 2021/10/26
* @Description: 圆角 span.
*/
class RadiusBackgroundSpan(
/**背景颜色*/
private val backgroundColor: Int = Color.parseColor("#00000000"),
/**圆角半径,单位 dp*/
private val radius: Int = 0,
/**文字大小,单位 dp*/
private val textSize: Float = 12f,
/**文字颜色*/
private val textColor: Int = Color.parseColor("#ffffff"),
/**文字水平间距,单位 dp*/
private val marginHorizontal: Int = 0
) : ReplacementSpan() {
private var mSize = 0
override fun getSize(
paint: Paint,
text: CharSequence?,
start: Int,
end: Int,
fm: Paint.FontMetricsInt?
): Int {
paint.textSize = DisplayUtil.dp2px(textSize).toFloat()
mSize = paint.measureText(text, start, end)
.toInt() + DisplayUtil.dp2px(marginHorizontal * 2.toFloat())
return mSize
}
override fun draw(
canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float,
top: Int, y: Int, bottom: Int, paint: Paint
) {
text?.let {
paint.isAntiAlias = true
paint.textSize = DisplayUtil.dp2px(textSize).toFloat()
val baseLineY = (bottom - top) / 2 + abs(paint.ascent() + paint.descent()) / 2
// 绘制圆角背景.
paint.color = backgroundColor
val oval = RectF(x, baseLineY + paint.ascent(), x + mSize, baseLineY + paint.descent())
canvas.drawRoundRect(oval, radius.toFloat(), radius.toFloat(), paint)
// 绘制文字.
paint.color = textColor
canvas.drawText(
text, start, end,
x + DisplayUtil.dp2px(marginHorizontal.toFloat()), baseLineY,
paint
)
}
}
}
|