Java Graphics: Constructing FontMetrics from Font, without a Graphics2D

3.2k Views Asked by At

Known

Given FontMetrics

There is a protected constructor for FontMetrics from Font.

Question:

Given a Font object, is there a way to construct a FontMetrics object without going through Graphics2D.setFont, Graphics2D.getFontMetric()?

Context

I'm playing with a TeX like rendering algorithm. I need to calculate bounding boxes & the such for various characters from a *.pfb file. I can construct a Font object from the *.pfb file. I need a FontMetrics object to get the ascent, descent, width. It just seems very ugly for me to have to construct an unused intermediate Graphics object just to get at the FontMetrics.

2

There are 2 best solutions below

2
On BEST ANSWER

Given a Font object, is there a way to construct a FontMetrics object without going through Graphics2D.setFont, Graphics2D.getFontMetric()?

See BufferedImage.createGraphics() or getGraphics() for an alternative way to get the Graphics instance.

0
On

Or completely without the use of the graphics object:

Font font = new Font("Helvetica",Font.PLAIN,12);
Canvas c = new Canvas();
FontMetrics fm = c.getFontMetrics(font);

If you now call c.getGraphics() it will return null. This (canvas) will also work in headless mode.