Java - 没有图形的 FontMetrics

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2843601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:06:23  来源:igfitidea点击:

Java - FontMetrics without Graphics

javaawtfont-sizefontmetrics

提问by piotrek

How to get FontMetrics without use Graphics ? I want to get FontMetrics in constructor, now I do this way:

如何在不使用 Graphics 的情况下获得 FontMetrics ?我想在构造函数中获取 FontMetrics,现在我这样做:

BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
FontMetrics fm = bi.getGraphics().getFontMetrics(font);
int width = fm.stringWidth(pattern);
int height = fm.getHeight();

采纳答案by amorfis

Hmm... It is quite logical that you need graphics to get FontMetrics. Font height, width etc. can differ on various displays.

嗯...您需要图形来获取 FontMetrics 是很合乎逻辑的。字体高度、宽度等在各种显示器上可能不同。

If you have some Component, you can use it for getting FontMetrics:

如果你有一些组件,你可以用它来获取 FontMetrics:

component.getFontMetrics(font);

回答by Lonzak

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 now call c.getGraphics()it will return null. Instead canvas will also work in headless mode.

如果您现在调用c.getGraphics()它将返回 null。相反,画布也可以在无头模式下工作。