The mice answer is great... And here is the description of the real problem:
The short simple answer is that Paint.getTextBounds(String text, int start, int end, Rect bounds)
returns Rect
which doesn't starts at (0,0)
. That is, to get actual width of text that will be set by calling Canvas.drawText(String text, float x, float y, Paint paint)
with the same Paint object from getTextBounds() you should add the left position of Rect. Something like that:
public int getTextWidth(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, end, bounds);
int width = bounds.left + bounds.width();
return width;
}
Notice this bounds.left
- this the key of the problem.
In this way you will receive the same width of text, that you would receive using Canvas.drawText()
.
And the same function should be for getting height
of the text:
public int getTextHeight(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, end, bounds);
int height = bounds.bottom + bounds.height();
return height;
}
P.s.: I didn't test this exact code, but tested the conception.
Much more detailed explanation is given in this answer.