Skip to content

Instantly share code, notes, and snippets.

@tcw165
Created December 7, 2020 03:49
Show Gist options
  • Save tcw165/0ab2fce16499cd0c6aaa43da5ffa6627 to your computer and use it in GitHub Desktop.
Save tcw165/0ab2fce16499cd0c6aaa43da5ffa6627 to your computer and use it in GitHub Desktop.
import android.graphics.Canvas
import android.graphics.Paint
import android.text.style.ReplacementSpan
import kotlin.math.ceil
/**
* Spans for annotating the TextView or EditText with a character.
*/
internal class CharAnnotationSpan(
private val symbol: Char,
private val isPrepend: Boolean = true
) : ReplacementSpan() {
private val textBuilder = StringBuilder()
override fun getSize(
paint: Paint,
text: CharSequence,
start: Int,
end: Int,
fm: Paint.FontMetricsInt?
): Int {
textBuilder.apply {
setLength(0)
if (isPrepend) {
append(symbol)
append(text, start, end)
} else {
append(text, start, end)
append(symbol)
}
}
return ceil(paint.measureText(textBuilder.toString(), 0, textBuilder.length)).toInt()
}
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
canvas.drawText(textBuilder.toString(), 0, textBuilder.length, x, y.toFloat(), paint)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment