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.
One of the best anime ever!!!
Touch OST
Drawing text can be tricky at times, let’s look at some examples.
First, let’s look at some terminologies used here.
Some most important keywords are:
baseline: the line where the text “sits on” ascent: The recommended distance above the baseline for singled spaced text descent: The recommended distance below the baseline for singled spaced text top: The maximum distance above the baseline for the tallest glyph in the font at a given text size bottom: The maximum distance below the baseline for the lowest glyph in the font at a given text size A picture is worth 1000 words:
You: Master, I heard this PECS in the JAVA world. But I’m deeply puzzled by it.
Master: Do you know what it stands for?
You: Producer Extends Consumer Super?
Master: In order to understand it, you shall stop thinking about what these words mean, it’s not helpful at all. Just follow my questions.
You: Yes, Master. Please start.
Master: There are plants, then there are fruits, then there are apples and pears.