Sunday, 29 December 2019

Measuring tight bounds box of multiline text

I'm drawing a multiline text on a canvas using StaticLayout, and I want to measure the most tight bounds box around the text before drawing, (the text could be in different sizes, fonts, styles etc...), I want something like that:

Size measureText(String text, float size, Font font, etc...)

and I want it to return the most tight bounds box around the text, i.e. (if we are talking about the pixels of the text):

(leftest_pixel - rightest_pixel, highest_pixel - lowest_pixels)

If the text was single line, I could do:

Paint paint = new Paint();
...
paint.getTextBounds(text, 0, size, rect);

But since the text could have multiple lines I must take in consider the linespacing and the glyphs descent and all the other font parameters... so the next option will be to use StaticLayout with maximalLineWidth (in order to break the lines), but StaticLayout doesn't calculate the most tight box, it will add a bit paddings in the top and in the bottom (because it basically multiple the number of lines by the max line height):

for example, the green box is the result of measuring with StaticLayout and the red box is the box I want to receive:

enter image description here enter image description here enter image description here

How can I do it? Thanks.



from Measuring tight bounds box of multiline text

No comments:

Post a Comment