37

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();
tangens
  • 39,095
  • 19
  • 120
  • 139
piotrek
  • 1,333
  • 4
  • 17
  • 35

2 Answers2

42

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.

Lonzak
  • 9,334
  • 5
  • 57
  • 88
  • 2
    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);` – Nathan Crause Aug 30 '20 at 02:48
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);
amorfis
  • 15,390
  • 15
  • 77
  • 125