我试着在我创建的表面视图上写一些文字。它的工作正常,如果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());
}
答案 0 :(得分:24)
你可以尝试使用以下内容来绘制带有换行符的文本:
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();
}
}
答案 1 :(得分:8)
在行之间添加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;
}
}
答案 2 :(得分:4)
继续改善Dee和FrinkTheBrave的答案。我在方法中添加了一个Rect,允许在特定宽度区域内绘图。将查看修改它以选择合适的字体大小并确保它适合正确的高度区域。
这将允许您指定要写入的行的宽度,这对于将未格式化的文本字符串拆分为类似的长度行并将其绘制到画布非常有用。
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(" ");
// set height of each line (height of text + 20%)
lineHeight = (int) (calculateHeightFromFontSize(str, fontSize) * 1.2);
// draw each line
String line = "";
for (int i = 0; i < lines.length; ++i) {
if(calculateWidthFromFontSize(line + " " + lines[i], fontSize) <= drawSpace.width()){
line = line + " " + lines[i];
}else{
canvas.drawText(line, x, y + yoffset, paint);
yoffset = yoffset + lineHeight;
line = lines[i];
}
}
canvas.drawText(line, x, y + yoffset, paint);
}
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());
}
此答案包含此用户在以前的回答中找到的优秀代码段:user850688 https://stackoverflow.com/a/11353080/1759409
答案 3 :(得分:1)
[]符号可能是你的换行符。无论出于何种原因,drawText()都不知道如何处理换行符。
剥离换行符,或者使用偏移Y位置调用drawText()两次以模拟换行符。