Java - FontMetrics without Graphics
Asked Answered
S

2

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();
Smallscale answered 16/5, 2010 at 11:54 Comment(3)
Why do you want to do this without graphics?Achelous
I create my own control, and I want to set preffred size in constructorSmallscale
This is useful for getting font metrics when in a headless mode, i.e. a command line tool that processes fonts to bitmaps.Grafting
F
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);
Fetter answered 16/5, 2010 at 12:2 Comment(1)
@Fetter Are you sure that font width and height depend on display while I have specified the font-size?Anastaciaanastas
M
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.

Mechanize answered 8/8, 2013 at 9:56 Comment(1)
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);Infective
F
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);
Fetter answered 16/5, 2010 at 12:2 Comment(1)
@Fetter Are you sure that font width and height depend on display while I have specified the font-size?Anastaciaanastas

© 2022 - 2024 — McMap. All rights reserved.