Found a simple and not slow method of determining text width/height drawn with specific Paint
that doesn't use StaticLayout
.
public int getTextWidth(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int width = bounds.left + bounds.width();
return width;
}
public int getTextHeight(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.bottom + bounds.height();
return height;
}
The short simple description of trick: 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
.
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()
.
Much more detailed explanation is given in this answer.