Created
August 5, 2021 01:12
-
-
Save darylsze/d3d4d32e4292c3bb19b517aabe3f105a to your computer and use it in GitHub Desktop.
RoundedBackgroundSpan
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.graphics.* | |
import android.text.style.ReplacementSpan | |
import kotlin.math.roundToInt | |
class RoundedBackgroundSpan( | |
private val context: Context, | |
private val borderRadius: Float = 0f, | |
private val backgroundColorInt: Int? = null, | |
private val textColorInt: Int = Color.BLACK, | |
private val textSizePx: Float = R.dimen._12sdp.dimen2Pixel(context).toFloat() | |
) : ReplacementSpan() { | |
private val paddingHorizontal = R.dimen._3sdp.dimen2Pixel(context) | |
private val paddingVertical = R.dimen._1sdp.dimen2Pixel(context) | |
private val marginVertical = R.dimen._1sdp.dimen2Pixel(context) | |
private val textPaint = Paint().apply { | |
color = textColorInt | |
textSize = textSizePx | |
flags = Paint.ANTI_ALIAS_FLAG | |
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) | |
} | |
private val backgroundPaint = Paint().apply { | |
backgroundColorInt?.apply { color = this } | |
flags = Paint.ANTI_ALIAS_FLAG | |
} | |
override fun getSize( | |
paint: Paint, | |
text: CharSequence?, | |
start: Int, | |
end: Int, | |
fm: Paint.FontMetricsInt? | |
): Int { | |
return (paint.measureText(text, start, end) + paddingHorizontal * 2).toInt() | |
} | |
private fun measureTextWidth(paint: Paint, text: CharSequence?, start: Int, end: Int): Float { | |
return paint.measureText(text, start, end) | |
} | |
override fun draw( | |
canvas: Canvas, | |
text: CharSequence?, | |
start: Int, | |
end: Int, | |
x: Float, | |
top: Int, | |
y: Int, | |
bottom: Int, | |
paint: Paint | |
) { | |
val rect = RectF( | |
x, | |
top + paddingVertical.toFloat() + marginVertical, | |
x + measureTextWidth(paint, text, start, end) + paddingHorizontal * 2, | |
bottom - paddingVertical.toFloat() - marginVertical | |
) | |
canvas.drawRoundRect( | |
rect, | |
borderRadius, | |
borderRadius, | |
backgroundPaint | |
) | |
canvas.drawText( | |
text ?: "", | |
start, | |
end, | |
x + paddingHorizontal + paddingHorizontal / 2, | |
y.toFloat() - paddingVertical * 2, | |
textPaint | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment