I designed a better way (I can't really say if it's better or not, but this method should be easy) for multi-line text in a canvas, like in a SurfaceView.
Here would be the code:
public class MultiLineText implements ObjectListener {
private String[] lines;
private float x, y, textSize;
private int textColor;
private float currentY;
public MultiLineText(String[] lines, float x, float y, float textSize, int textColor) {
this.lines = lines;
this.x = x;
this.y = y;
this.textSize = textSize;
this.textColor = textColor;
}
@Override
public void draw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(textColor);
paint.setTextSize(textSize);
currentY = y;
for (int i = 0; i < lines.length; i++) {
if (i == 0)
canvas.drawText(lines[i], x, y, paint);
else {
currentY = currentY + textSize;
canvas.drawText(lines[i], x, currentY, paint);
}
}
}
@Override
public void update() {
}
}
Import the 2 classes with import android.graphics.Canvas;
and import android.graphics.Paint;
to make sure no errors can occur.
On the easy hand, create an Interface Class named "ObjectListener" (or whatever you want to call it, just change the name then), and add two following lines of code:
void draw(Canvas canvas);
void update();
To implement this, use this code in the View or your Renderer on draw(Canvas canvas)
method:
new MultiLineText(new String[]{
"This is a multi-line text.",
"It's setup is basic. Just do the following code,",
"and you would be done."
}, 150, 150, 32, Color.WHITE).draw(canvas);
Sorry, I just wanted to implement this text, so yeah...
You can change the X and Y coordinates from 150 to your liking. A text Size of 26 is readable, and it is not too big because Canvas renders in a small text by default.
Layout
instead of callingCanvas.drawText
directly. This Q&A shows how to use aStaticLayout
to draw multiline text.