Search code examples
javaswingfontsawtfontmetrics

Java Graphics: Constructing FontMetrics from Font, without a Graphics2D


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.


Solution

  • 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.