How do I get the size of a string in pixels using Java2D?
With java.awt.FontMetrics
[link]http://java.sun.com/j2se/1.4.2/docs/api/java/awt/FontMetrics.html[/link]
Or simply:
Font.getStringBounds(String str, FontRenderContext frc)
which simply returns a Rectangle2D object that gives you the width and height of the text to draw/blit. The FontRenderContext can be provided from the Graphics2D object.
Note that getStringBounds does not necessarily enclose all of the pixels that would be drawn, rather it helps align the given text with another piece. To find a bounding rectangle of the drawing you need to use GlyphVector.getPixelBounds or TextLayout.getBounds
Thanks guys
[quote]Note that getStringBounds does not necessarily enclose all of the pixels that would be drawn, rather it helps align the given text with another piece. To find a bounding rectangle of the drawing you need to use GlyphVector.getPixelBounds or TextLayout.getBounds
[/quote]
Ho I did’t know that! I learned this technique from Java2D Graphics published by O’Reilly.
int width = g2d.getFontMetrics().stringWidth(String string);
Much of the time it doesn’t make much difference. The usual symptom of using the wrong method, is chopping off bits of italic characters.