我试着在我创建的表面视图上写一些文字.它的工作正常,如果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)
迪的答案很棒.以下代码基于dee的答案,但对个人偏好进行了一些修改:
在线之间增加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)| 归档时间: |
|
| 查看次数: |
11678 次 |
| 最近记录: |