Tôi gặp sự cố tương tự. Một trong những giải pháp đầu tiên của tôi là sau.
/**
* 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);
}
gì là mất tích:
- Không có cơ chế phá vỡ dòng thông minh, vì nó phá vỡ dựa trên maxWidth
Làm thế nào để gọi?
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);
Tôi có một lớp tĩnh gọi là CanvasUtils nơi tôi đóng gói những thứ như thế này. Về cơ bản tôi vẽ văn bản trong một hình chữ nhật. Đây là lý do textHeight là chiều cao của văn bản. Nhưng bạn có thể chuyển những gì bạn muốn cho hàm.
Lập trình tốt!
Nguồn
2015-08-14 19:06:56
Xem câu trả lời này cho một ví dụ sử dụng tốt về 'StaticLayout's: http://stackoverflow.com/a/8369690/293280 –