Java - FontMetrics without Graphics
19,076
Solution 1
Hmm... It is quite logical that you need graphics to get FontMetrics. Font height, width etc. can differ on various displays.
If you have some Component, you can use it for getting FontMetrics:
component.getFontMetrics(font);
Solution 2
No you do not necessarily need to get/use the graphics object:
Font font = new Font("Helvetica",Font.PLAIN,12);
Canvas c = new Canvas();
FontMetrics fm = c.getFontMetrics(font);
If you would now call c.getGraphics()
it would return null. The canvas solution on the other hand will also work in headless mode.
Author by
piotrek
Updated on June 13, 2022Comments
-
piotrek about 2 years
How to get FontMetrics without use Graphics ? I want to get FontMetrics in constructor, now I do this way:
BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB); FontMetrics fm = bi.getGraphics().getFontMetrics(font); int width = fm.stringWidth(pattern); int height = fm.getHeight();
-
Mohammed Shareef C about 7 years@amorfis Are you sure that font width and height depend on display while I have specified the font-size?
-
Nathan Crause almost 4 yearsIf I may expand ever so slightly on this - if you're reading a font from a file, remember to "derive" a font with a viable size (failing to remember to do so will result in values such as getMaxAscent/Descent returning 1):
Font sourceFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
Font awtFont = sourceFont.deriveFont(72.0f);
Canvas canvas = new Canvas();
FontMetrics metrics = canvas.getFontMetrics(awtFont);