9

我看过很多处理类似问题的帖子,但没有一个对我有用。在Canvas中,我有一个大小为 200 像素 x 200 像素的矩形,我想在这个矩形中写入文本。文本不需要填满整个矩形,但重要的是当它到达矩形的末尾时应该自动换行。我怎样才能在 Android 中做到这一点?

4

4 回答 4

32

您可以使用静态布局

RectF rect = new RectF(....)

StaticLayout sl = new StaticLayout("This is my text that must fit to a rectangle", textPaint, (int)rect.width(), Layout.Alignment.ALIGN_CENTER, 1, 1, false);

canvas.save();
canvas.translate(rect.left, rect.top);
sl.draw(canvas);
canvas.restore();
于 2012-10-16T18:21:00.967 回答
3

您需要测量文本,然后在代码中自行分解。 Paint.measureText是您所需要的。

于 2012-10-16T18:11:25.943 回答
1
public class MutilineText {
private String mText;
private int fontSize = 50;


public MutilineText(String text) {

    this.mText = text;
}

public String getText() {
    return mText;
}

public void setText(String text) {
    mText = text;
}

public void draw(Canvas canvas, Rect drawSpace) {


    Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);

    paintText.setAntiAlias(true);
    paintText.setDither(true);
    paintText.setColor(Color.BLACK);
    paintText.setStyle(Paint.Style.FILL);
    paintText.setStrokeWidth(3);
    paintText.setTextSize(fontSize);
    drawMultilineText(mText, drawSpace.left, drawSpace.top + 15, paintText, canvas, fontSize, drawSpace);
}


private void drawMultilineText(String str, int x, int y, Paint paint, Canvas canvas, int fontSize, Rect drawSpace) {
    int lineHeight = 0;
    int yoffset = 0;
    String[] lines = str.split("\n");

    lineHeight = (int) (calculateHeightFromFontSize(str, fontSize) * 1.4);
    String line = "";
    for (int i = 0; i < lines.length; ++i) {
        if (calculateWidthFromFontSize(line, fontSize) <= drawSpace.width()) {
            canvas.drawText(line, x + 30, y + yoffset, paint);
            yoffset = yoffset + lineHeight;
            line = lines[i];
        } else {
            canvas.drawText(divideString(line, drawSpace.width()), x + 30, y + yoffset, paint);
        }
    }


}

private String divideString(String inputString, int bound) {
    String ret = inputString;

    while (calculateWidthFromFontSize(ret, fontSize) >= bound) {
        ret = ret.substring(0, (ret.length() - 1));
    }
    ret = ret.substring(0, ret.length() - 3) + "...";

    return ret;
}

private int calculateWidthFromFontSize(String testString, int currentSize) {
    Rect bounds = new Rect();
    Paint paint = new Paint();
    paint.setTextSize(currentSize);
    paint.getTextBounds(testString, 0, testString.length(), bounds);

    return (int) Math.ceil(bounds.width());
}

private int calculateHeightFromFontSize(String testString, int currentSize) {
    Rect bounds = new Rect();
    Paint paint = new Paint();
    paint.setTextSize(currentSize);
    paint.getTextBounds(testString, 0, testString.length(), bounds);

    return (int) Math.ceil(bounds.height());
}
于 2016-06-17T16:40:32.777 回答
0

您是否可以在画布顶部使用文本字段并为该文本字段启用多行 - 然后您将在文本字段中完成换行符是免费的;-)

于 2012-10-16T18:18:03.990 回答