Tuve el mismo problema. Una de mi primera solución es seguir.
/**
* This function draws the text on the canvas based on the x-, y-position.
* If it has to break it into lines it will do it based on the max width
* provided.
*
* @author Alessandro Giusa
* @version 0.1, 14.08.2015
* @param canvas
* canvas to draw on
* @param paint
* paint object
* @param x
* x position to draw on canvas
* @param y
* start y-position to draw the text.
* @param maxWidth
* maximal width for break line calculation
* @param text
* text to draw
*/
public static void drawTextAndBreakLine(final Canvas canvas, final Paint paint,
final float x, final float y, final float maxWidth, final String text) {
String textToDisplay = text;
String tempText = "";
char[] chars;
float textHeight = paint.descent() - paint.ascent();
float lastY = y;
int nextPos = 0;
int lengthBeforeBreak = textToDisplay.length();
do {
lengthBeforeBreak = textToDisplay.length();
chars = textToDisplay.toCharArray();
nextPos = paint.breakText(chars, 0, chars.length, maxWidth, null);
tempText = textToDisplay.substring(0, nextPos);
textToDisplay = textToDisplay.substring(nextPos, textToDisplay.length());
canvas.drawText(tempText, x, lastY, paint);
lastY += textHeight;
} while(nextPos < lengthBeforeBreak);
}
Lo que falta:
- Sin mecanismo de ruptura de línea inteligente, ya que rompe basa en la anchoMax
Cómo llamar?
paint.setTextSize(40);
paint.setColor(Color.WHITE);
paint.setSubpixelText(true);
float textHeight = paint.descent() - paint.ascent();
CanvasUtils.drawTextAndBreakLine(canvas, paint, this.left,
textHeight, this.displayWidth, this.text);
Tengo una clase estática llamada CanvasUtils donde encapsulo cosas como esta. Básicamente dibujo el texto dentro de un rectángulo. Esta es la razón por la cual textHeight es la altura del texto. Pero puedes pasar lo que quieras a la función.
¡Buena programación!
Vea esta respuesta para un buen ejemplo de uso de 'StaticLayout's: http://stackoverflow.com/a/8369690/293280 –