package com.adealink.weparty.commonui.widget

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.text.style.ReplacementSpan

/**
 * Created by PengWuLiang on 2025/4/8
 */
class RoundBackgroundSpan(
    private val textColor: Int,
    private val bgColor: Int,
    private val radius: Float,
    private val padding: Float = 0f
) : ReplacementSpan() {

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

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        val textWidth = paint.measureText(text, start, end)

        // 修正后的矩形坐标计算
        val rect = RectF(
            x - padding,
            y + paint.ascent() - padding,  // 根据基线位置计算顶部
            x + textWidth + padding,
            y + paint.descent() + padding  // 根据基线位置计算底部
        )

        paint.color = bgColor
        canvas.drawRoundRect(rect, radius, radius, paint)

        // 绘制文字
        paint.color = textColor // 恢复原始文字颜色
        canvas.drawText(text, start, end, x + padding, y.toFloat(), paint)
    }
}