美文网首页
自定义ReplacementSpan实现圆形Background

自定义ReplacementSpan实现圆形Background

作者: 半截铅笔 | 来源:发表于2018-11-05 19:24 被阅读16次

项目需要实现如下UI.通过自定义ReplacementSpan实现.

图片.png
class RoundBackgroundColorSpan(
        context: Context,
        bgColorResId: Int,
        textColorResId: Int)
    : ReplacementSpan() {

    private var mBgColor: Int = ContextCompat.getColor(context, bgColorResId)
    private var mTextColor: Int = ContextCompat.getColor(context, textColorResId)

    override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
        return paint.measureText(text, start, end).toInt();
    }

    override fun draw(canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
       //记录原始配置值~
        val originalColor = paint.color
        val originalTextSize = paint.textSize
        val originalBottom = paint.fontMetrics.bottom
        //高度~
        val height = bottom - top
        //半径~
        var radius = height / 2f - 1
        //缩放值~
        mScale = contextSize / paint.textSize
        if (mScale > 1) {
            mScale = 1f
        }

        paint.textSize = contextSize.toFloat()
        //记录文字的偏移量~
        val excursionL = paint.measureText(text, start, end) / 2f

        //计算缩放后的偏移量~
        val excursionP = (height - (paint.fontMetrics.bottom - paint.fontMetrics.top)) / 2

        paint.color = mBgColor
        //y 需要bottom
        canvas.drawCircle(x + excursionL, y + originalBottom - (height / 2), radius * mScale, paint)
        paint.color = mTextColor

        canvas.drawText(text, start, end, x, y - excursionP * mScale, paint)
        paint.color = originalColor
        paint.textSize = originalTextSize
    }
}

相关文章

网友评论

      本文标题:自定义ReplacementSpan实现圆形Background

      本文链接:https://www.haomeiwen.com/subject/ilhexqtx.html