Reputation: 498
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?
Upvotes: 7
Views: 2436
Reputation: 76281
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.
Upvotes: 4
Reputation: 109613
You can use javax.swing.SwingUtilities.layoutCompoundLabel
. Do not be deterred by the many parameters. There are two versions, the version with the JComponent (may be null) does more flags. It is used for JLabel, so quite versatile, and yields a Rectangle.
BTW That even on "a" a descender might be added to the bounds, is likely to happen here too. You could take the GlyphVector and calculate a bounding box there, but what when font hinting is on, so the pixel positions are slightly off, which error might accumulate over several chars?
Upvotes: 0