Multiline drawtext canvas

I am developing an image commentary application. I draw text in canvas usingcanvas.drawText(text, x, y, imgPaint);

This is displayed on one line. I need to split a line into multi-line when the text crosses the width of the canvas

Thanks in advance

+4
source share
2 answers

You need to use StaticLayout:

TextPaint mTextPaint=new TextPaint();
StaticLayout mTextLayout = new StaticLayout("my text\nNext line is very long text that does not definitely fit in a single line on an android device. This will show you how!", 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 = 100;
textY = 100;

canvas.translate(textX, textY);
mTextLayout.draw(canvas);
canvas.restore();
+7
source

You need to split the line and split each fragment separately with increasing y based on the font height.

For instance:

var lines = text.split("\n"),
    x = 100, y = 100, fHeight = 16, // get x, y and proper font or line height here
    i = 0, line;

while(line = lines[i++]) {
    canvas.drawText(line, x, y, imgPaint);
    y += fHeight;
}
+1
source

All Articles