Guowei Lv

1 minute read

Let’s take a look at what we are going to build.

The secret is to clip canvas before drawing the text!

private fun drawText(canvas: Canvas, paint: Paint, start: Int, end: Int) {
    canvas.save()

    rect.set(start, 0, end, height)
    canvas.clipRect(rect)

    val textString = text.toString()
    paint.getTextBounds(textString, 0, textString.length, bounds)

    val x = width / 2 - bounds.width() / 2

    val fontMetrics = changePaint.fontMetrics
    val dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
    val baseline = height / 2 + dy

    canvas.drawText(textString, x.toFloat(), baseline, paint)

    canvas.restore()
}

Full source code can be found here

comments powered by Disqus