Question

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.

Was it helpful?

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top