Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find true visible size of a text string in Java

Is it possible to find the true bounding box of a string in Java? ie the smallest rectangle which includes the pixels which actually get painted?

I have looked at FontMetrics and LineMetrics, and although they allow a string to be passed in, they don't appear to take account of the characters themselves, eh "a", "p" and "P" all return the same height.

Specifically, they seem to include the descent in the string height even if the actual character does not descend below the baseline. Are there other metrics I can access which return a true bounding box?

Alternatively, is there any way to tell if a particular character has a descender?

like image 488
Martin McBride Avatar asked Apr 13 '12 17:04

Martin McBride


1 Answers

See this tutorial on measuring text, which is heavily focused on FontMetrics.

The more advanced measurements (to get the bounding box of a particular string), then TextLayout is your friend, as explained here.

In addition to that tutorial on TextLayout, the javadoc contains examples of its use.

like image 122
daveb Avatar answered Nov 01 '22 05:11

daveb