38

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(); 
3
  • Why do you want to do this without graphics? Commented May 16, 2010 at 11:55
  • I create my own control, and I want to set preffred size in constructor Commented May 16, 2010 at 12:07
  • 8
    This is useful for getting font metrics when in a headless mode, i.e. a command line tool that processes fonts to bitmaps. Commented Oct 19, 2011 at 9:00

2 Answers 2

43

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If 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);
22

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); 

1 Comment

@amorfis Are you sure that font width and height depend on display while I have specified the font-size?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.