Java Graphics: Constructing FontMetrics from Font, without a Graphics2D

瘦欲@ 提交于 2019-12-19 10:53:06

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10677876/java-graphics-constructing-fontmetrics-from-font-without-a-graphics2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!