Nueva línea al pintar un texto en una imagen

Tengo una aplicación que el usuario inserta un texto, y cuando hace clic en un botón, genera una nueva imagen con ese texto en una imagen predeterminada y la guarda en el teléfono.

Pero a veces ese texto es demasiado largo y supera el ancho de la imagen, así que lo que estoy tratando de hacer es dividirlo en una nueva línea. ¿Cómo debo hacerlo?

He intentado con breakText, pero no estoy seguro de cómo usarlo … Yo estaba usando:

textPaint.breakText(text[2], true, bmp.getWidth(), null); 

Pero no funcionó.

También, cuando rompo manualmente la línea en el EditText demuestra todo en solamente uno y con un "[]" donde la segunda línea debe comenzar …

EDIT: Mi código original:

  private void SaveMyImage() { // TODO Auto-generated method stub File myDir = new File(Environment.getExternalStorageDirectory().getPath()+"/App/"); myDir.mkdirs(); File file = new File (myDir, fname); if (file.exists ()) file.delete (); try { FileOutputStream out = new FileOutputStream(file); Canvas canvas = new Canvas(bmp); Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); if (text[0].equals("Image 01")) { textPaint.setColor(Color.BLACK); } else { textPaint.setColor(Color.WHITE); } textPaint.setTextAlign(Align.CENTER); textPaint.setTextSize(tamanho); textPaint.setShadowLayer(2, 2, 2, Color.BLACK); textPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern canvas.drawBitmap(bmp, 0, 0, null); canvas.drawText(text[1], largura, altura2, textPaint); canvas.drawText(text[2], largura, altura, textPaint); bmp.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); Toast.makeText(SaveIMG.this, "Image saved on phone", Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } sendBroadcast(new Intent( Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/App/"+fname); pronto.setImageURI(uri); } 

BreatText devuelve el número de caracteres en la cadena que se puede mostrar si antes de ser cortado. Yo sugeriría que lo llamara en un bucle. Eliminar sin embargo muchos caracteres que puede encajar y colocarlos en una cadena de cada iteración hasta que el texto fuente está vacío .:

 ArrayList<String> lines = new ArrayList<String>(); String test = text[2]; while(!test.isEmpty()){ int newLength = textPaint.breakText(test, true, bmp.getWidth(), null); lines.add(test.substring(0, newLength)); test = test.substring(newLength); } 

En cuanto a la impresión de varias líneas. Supongo que está usando Canvas.drawText que no parece apoyar los saltos de línea. Así que necesitarás dibujar cada línea por separado con diferentes Valores Y. (Código adaptado de aquí):

 Rect bounds = new Rect(); int yoff = 0; for(String line:lines){ canvas.drawText(line, x, y + yoff, paint); textPaint.getTextBounds(line, 0, line.length(), bounds); yoff += bounds.height(); } 

EDIT No veo en su código donde realmente dividir las cadenas como he descrito. No puedo diagnosticar por qué mi solución no funcionó si en realidad no me muestra cómo se implementó.

Trabajando desde aquí aunque creo que puedo mostrarle cómo solucionar el error. Si desea hacerlo varias veces sería una buena idea escribir un método para ello. Agregue el siguiente método a su clase:

 public void splitAndDrawLines(Canvas canvas,String text, int x, int y, Paint textPaint, int width){ ArrayList<String> lines = new ArrayList<String>(); String test = text; while(!test.isEmpty()){ int newLength = textPaint.breakText(test, true, canvas.getWidth(), null); lines.add(test.substring(0, newLength)); test = test.substring(newLength); } Rect bounds = new Rect(); int yoff = 0; for(String line:lines){ canvas.drawText(line, x, y + yoff, textPaint); textPaint.getTextBounds(line, 0, line.length(), bounds); yoff += bounds.height(); } } 

Reemplazar este código:

 canvas.drawText(text[1], largura, altura2, textPaint); canvas.drawText(text[2], largura, altura, textPaint); 

Con este código:

 this.splitAndDrawLines(canvas, text[1], largura, altura2, textPaint); this.splitAndDrawLines(canvas, text[2], largura, altura, textPaint); 

EDIT 2:

Aquí está el código que usé para configurar y escribir el código:

  // Create a 100x100 bitmap bmp = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); // Set the height of the text to 12. this.tamanho = 12f; // Draw the text in the middle of the picture width-wise. this.largura = bmp.getWidth() / 2; // Text parameters this.text = new String[]{"MAKE THE TEXT WHITE", "This text starts in the middle of the middle is too long and will be split","Short text at the top of the image"}; // Start one line size into the picture height-wise. this.altura = this.tamanho; // Start in the middle of the picture height-wise. this.altura2 = bmp.getHeight()/2; // Output File name. this.fname = "TEST.jpg"; // Save the image SaveMyImage(); 

Encontré una solución, creé una disposición y fijé la secuencia como textview y la imagen como fondo y la dibujé.

Trabajo de fino Consulte este LINK . Espero que sea útil.

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.