В документации указано, что int end «1 за последним символом в строке для измерения». http://developer.android.com/reference/android/graphics/Paint.html#getTextBounds(java.lang.String, Int, Int, android.graphics.Rect)
Вы должны иметь:
textView.getPaint().getTextBounds(text, 0, text.length(), rect);
Это также относится и к Canvas.drawText().
Текст, отображающий текст, будет «обертывать» текст. Метод getTextBounds вообще не знает TextView.
Фактически, если бы вы создали собственный пользовательский вид для отображения текста, getTextBounds был бы очень полезен для достижения вашей собственной текстовой упаковки. Следующий код выполняет ужасную работу с презентацией, но выполняет итерацию по строкам, разделяя их на холст, эффективно обертывая текст.
private void drawText(Canvas canvas) {
String text = "Nunc eleifend erat eu nulla varius iaculis. Quisque feugiat justo sit amet" +
" neque interdum tempor. Curabitur faucibus facilisis tristique. Donec posuere" +
" viverra magna, eu accumsan sapien congue id. Cras fringilla justo ut lacus" +
" molestie, et venenatis orci egestas. Vivamus pretium, nisl quis cursus cursus," +
" dolor eros porta neque, sit amet viverra ante orci non elit. Donec odio neque," +
" volutpat sit amet dui sit amet, fringilla tempus sapien. Donec sed mollis justo." +
" In dignissim tincidunt neque, eu luctus justo egestas nec. Donec commodo ut arcu" +
" vel placerat. Donec ullamcorper justo eget justo commodo hendrerit. Quisque" +
" commodo imperdiet posuere. Aenean vehicula dui.";
Paint paint = new Paint();
paint.setTextSize(30);
paint.setAntiAlias(true);
int padding = 20;
int availWidth = getWidth() - 2 * padding;
int availHeight = getHeight() - 2 * padding;
Rect bounds = new Rect();
int currentTextBottom = 0;
int firstCharInLine = 0;
int lastCharInLine = 0;
outerLoop: while (currentTextBottom < availHeight) {
while (Character.isWhitespace(text.charAt(firstCharInLine))) {
lastCharInLine = ++firstCharInLine;
}
for (int i = firstCharInLine + 1; i < text.length(); i++) {
paint.getTextBounds(text, firstCharInLine, i, bounds);
if (bounds.width() <= availWidth) {
if (Character.isWhitespace(text.charAt(i))) {
lastCharInLine = i;
}
} else {
currentTextBottom += bounds.height();
if (firstCharInLine == lastCharInLine) {
lastCharInLine = i;
}
canvas.drawText(text, firstCharInLine, lastCharInLine, padding, currentTextBottom + padding, paint);
firstCharInLine = lastCharInLine++;
break;
}
if (i == text.length() - 1) {
currentTextBottom += bounds.height();
lastCharInLine = text.length();
canvas.drawText(text, firstCharInLine, lastCharInLine, padding, currentTextBottom + padding, paint);
break outerLoop;
}
}
}
}
}
EDIT - как примечание стороны, я только сейчас заметил разницу между bounds.width() и Paint.measureText (!) Полностью не связанный с вышеуказанным кодом, у меня были проблемы с Paint.Align.Center сбой и не всегда работали как ожидалось. Поэтому я удалил любое выравнивание текста и попытался:
canvas.drawText(
text,
viewWidth/2f - bounds.width()/2f,
viewHeight/2f + bounds.height()/2f,
paint);
Но это не выравнивается горизонтально. Когда я сделал это вместо:
float textWidth = paint.measureText(text);
canvas.drawText(
text,
viewWidth/2f - textWidth/2,
viewHeight/2f + bounds.height()/2f,
paint);
Он выровнен к моему удовольствию :)
Вы можете разместить полный код? Неясно, откуда берется значение в тексте. – Sebastian
@Sebastian: текст - это строка. длинная строка. Содержит около 1000 символов. – Ashwin