I need to find the width of the text that is drawn on the screen. This thread suggests that the FontMetrics.stringWidth() will sometimes not be as accurate as FontMetrics.getStringBounds().
Does anyone know if this is correct, and if it is, in which context is this difference visible? The FontMetrics.stringWidth() seems to be used more frequently, including in SwingUtilities.computeStringWidth(). Also, the obvious advantage is that it doesn't require Graphics object, but this itself combined with the fact that antialiasing and similar settings are defined in Graphics object might explain why FontMetrics.getStringBounds() might be more accurate.
A Font class is used to set the screen fonts and it maps the characters of the language to their respective glyphs whereas a FontMetrics class defines a font metrics object, which encapsulates information about the rendering of a particular font on a particular screen.
The abstract FontMetrics class provides the tools for calculating the actual width and height of text when displayed on the screen. You can use the results to position objects around text or to provide special effects like shadows and underlining. Like the Graphics class, FontMetrics is abstract.
Font metrics help the computer determine things like the default spacing between lines, how high or low sub and super scripts should go, and how to align two differently sized pieces of text next to each other. Visualizing a font's metrics, it looks a lot like guidelines in Sketch or Photoshop.
Note that the Baseline is what the first four are measured from. It is line which forms the base that the text sits on, even though some characters (like g, y, j, etc.) might have parts that go below the line.
getStringBounds
has more information to work with, since it gets passed a Graphics. It can use this for calculating sub-pixel glyph placement and to account for the effects of anti-aliasing on the glyph sizes. From the documentation for FontRenderContext:
Anti-aliasing and Fractional-metrics specified by an application can also affect the size of a character because of rounding to pixel boundaries.
I think the answer is in your question. From the javadocs:
stringWidth
Note that the total advance width returned from this method does not take into account the rendering context. Therefore, the anti-aliasing and fractional metrics hints can affect the value of the advance. When enabling the anti-aliasing and fractional metrics hints, use getStringBounds(String, Graphics) instead of this method. The advance of a String is not necessarily the sum of the advances of its characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With