开发者

Java - FontMetrics without Graphics

开发者 https://www.devze.com 2022-12-30 05:16 出处:网络
How to get FontMetrics without use Graphics ? I want to get FontMetrics in constructor, now I do this way:

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 = f开发者_如何学Gom.getHeight();


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号