Canvas.drawText(...)不打印换行符

6 android text canvas

我试着在我创建的表面视图上写一些文字.它的工作正常,如果title为false,并且没有为文本添加换行符.但是,如果我添加标题并因此添加换行符,则不会按预期打印换行符,而是打印此符号[].

任何提示为什么?

@Override
public void drawObject() {
String text = "";
if (title) {
   text = getGameBoard().getGame().getForeignProfile().getName() + "\n";
}
text = text + getScoreAsString();
getGameBoard().getCanvas().drawText(text, 0, text.length(), getPosition().getX(), getPosition().getY(), getPaint());
}
Run Code Online (Sandbox Code Playgroud)

dbo*_*tha 25

您可以尝试使用以下内容来绘制带有换行符的文本:

Rect bounds = new Rect();
void drawString(Canvas canvas, Paint paint, String str, int x, int y) {
    String[] lines = str.split("\n");

    int yoff = 0;
    for (int i = 0; i < lines.length; ++i) {
        canvas.drawText(lines[i], x, y + yoff, paint);
        paint.getTextBounds(lines[i], 0, lines[i].length(), bounds);
        yoff += bounds.height();
    }
}
Run Code Online (Sandbox Code Playgroud)


Fri*_*ave 9

迪的答案很棒.以下代码基于dee的答案,但对个人偏好进行了一些修改:

  1. 称之为drawMultilineText(因为它等同于drawText
  2. 将参数的顺序与drawText(文本,x,y,paint和canvas)相同
  3. 在开始时获取一次线高,因为从边界返回的高度取决于字母的高度,即e不如E高
  4. 在线之间增加20%的高度差距

    void drawMultilineText(String str, int x, int y, Paint paint, Canvas canvas) {
        int      lineHeight = 0;
        int      yoffset    = 0;
        String[] lines      = str.split("\n");
    
        // set height of each line (height of text + 20%)
        paint.getTextBounds("Ig", 0, 2, mBounds);
        lineHeight = (int) ((float) mBounds.height() * 1.2);
        // draw each line
        for (int i = 0; i < lines.length; ++i) {
            canvas.drawText(lines[i], x, y + yoffset, paint);
            yoffset = yoffset + lineHeight;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)


Tre*_*hns 1

[] 符号可能是您的换行符。无论出于何种原因,drawText() 不知道如何处理换行符。

要么去掉换行符,要么调用drawText()两次并使用Y位置偏移来模拟换行符。