studio drawtextonpath drawpoints drawpath drawables android canvas 2d

drawpoints - drawtextonpath android



Envolviendo texto largo en un Android Canvas (3)

Tengo un control personalizado que está realizando muchos dibujos en 2D directamente en el canvas .

Parte de este dibujo es texto, así que estoy usando el método Canvas.drawText() .

Quiero dibujar el texto dentro de algunos límites: arriba a la izquierda, cierto ancho máximo y un número máximo de líneas. Después de dibujar el texto, quiero saber cuántas líneas tomó.

¿Existe una función incorporada para dibujar texto dentro de límites haciendo la división de manera sensata?

Si no, ¿hay una receta estándar para hacerlo?


Puede usar Paint.getTextBounds () para medir el tamaño de toda la cadena o Paint.getTextWidths () para obtener el ancho de cada carácter. Luego, divida la cuerda apropiadamente antes de dibujarla.


Puedes usar la clase android.text.StaticLayout para esto; simplemente cree un StaticLayout para el texto deseado, alineación, ancho, etc. y llame a su método de draw(Canvas) para dibujar en el lienzo.


Yo tuve el mismo problema. Una de mis primeras soluciones es la siguiente.

/** * 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:

  • No hay un mecanismo de corte inteligente, ya que se rompe según el maxWidth

¿Como 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 que textHeight es la altura del texto. Pero puedes pasar lo que quieras a la función.

Buena programación!