我遇到了同样的问题。我的第一个解决方案之一是遵循。
/**
* 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);
}
缺少什么:
- 没有智能断线机制,因为它基于 maxWidth 进行断线
怎么打电话?
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);
我有一个名为 CanvasUtils 的静态类,我在其中封装了这样的东西。基本上我在一个矩形内绘制文本。这就是 textHeight 是文本高度的原因。但是你可以将你想要的传递给函数。
编程不错!