What is the difference between FontMetrics.stringWidth() and FontMetrics.getStringBounds()?
Asked Answered
D

2

5

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.

Daune answered 15/8, 2011 at 1:56 Comment(1)
See also this Q&A.Negris
H
6

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.

Hamiltonian answered 15/8, 2011 at 2:5 Comment(0)
I
5

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.

Influent answered 15/8, 2011 at 2:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.