开发者

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

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 advant开发者_开发知识库age 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜