It is not supported to use \n to wrap the text to be drawn in the Canvas drawText method, but you can do this yourself.

The first way

The first method can be supported directly by using TextPaint. This method is more convenient and supports all symbols directly.

TextPaint textPaint = new TextPaint(); textPaint.setARGB(0xFF, 0, 0, 0); TextPaint. SetTextSize (20.0 F); textPaint.setAntiAlias(true); StaticLayout layout = new StaticLayout(" ABC \r\ N123 ", textPaint, 300, ALIGN_NORMAL, 1.0f, 0.0f, true); canvas.save(); canvas.translate(20, 20); layout.draw(canvas); canvas.restore();Copy the code

The second method is to divide the String to be drawn with \n, and then draw parts of it. After drawing a part of it, manually wrap it.

String[] strings = text.split("\n");
Paint.FontMetrics fm = paint.getFontMetrics();
float offsetY = fm.descent - fm.ascent;
 for (String s : strings) {
     canvas.drawText(s , i, 1, currentX, currentY - ascent, paint);
     currentY += offsetY;
     offsetY = 0;
     currentX = 0;
}

Copy the code

CurrentX and currentY are global coordinates drawn on each line. The currentX is reset on each newline. The currentX can be set according to its left, right, or center position.

The second way

The second method is more primitive, although can be implemented, but also limited to support \n, with a new symbol to add new logic, more trouble, the first method is more convenient, if you can achieve the required effect, the first method is more convenient.