Draw multi-line text to Canvas
Solution 1:
I found another way using static layouts. The code is here for anyone to refer to:
TextPaint mTextPaint=new TextPaint();
StaticLayout mTextLayout = new StaticLayout(mText, mTextPaint, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
canvas.save();
// calculate x and y position where your text will be placed
textX = ...
textY = ...
canvas.translate(textX, textY);
mTextLayout.draw(canvas);
canvas.restore();
Solution 2:
Just iterate through each line:
int x = 100, y = 100;
for (String line: text.split("\n")) {
canvas.drawText(line, x, y, mTextPaint);
y += mTextPaint.descent() - mTextPaint.ascent();
}
Solution 3:
Unfortunately Android doesn't know what \n
is. What you have to do is strip the \n
and then offset the Y to get your text on the next line. So something like this:
canvas.drawText("This is", 100, 100, mTextPaint);
canvas.drawText("multi-line", 100, 150, mTextPaint);
canvas.drawText("text", 100, 200, mTextPaint);