java Java中的字符串长度(以像素为单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13345712/
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
String length in pixels in Java
提问by APerson
Is there a way to calculate the length of a string in pixels, given a certain java.awt.Font
object, that does not use any GUI components?
有没有办法计算一个字符串的长度(以像素为单位),给定一个java.awt.Font
不使用任何 GUI 组件的对象?
采纳答案by Brian
that does not use any GUI components?
不使用任何 GUI 组件?
It depends on what you mean here. I'm assuming you mean you want to do it without receiving a HeadlessException
.
这取决于你在这里的意思。我假设你的意思是你想在没有收到HeadlessException
.
The best way is with a BufferedImage
. AFAIK, this won't throw a HeadlessException
:
最好的方法是使用BufferedImage
. AFAIK,这不会抛出HeadlessException
:
Font font = ... ;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
FontMetrics fm = img.getGraphics().getFontMetrics(font);
int width = fm.stringWidth("Your string");
Other than using something like this, I don't think you can. You need a graphics context in order to create a FontMetrics
and give you font size information.
除了使用这样的东西,我认为你不能。您需要一个图形上下文来创建一个FontMetrics
并为您提供字体大小信息。
回答by dacwe
You can use the Graphics2D
object to get the font bounds (including the width):
您可以使用该Graphics2D
对象来获取字体边界(包括宽度):
Graphics2D g2d = ...
Font font = ...
Rectangle2D f = font.getStringBounds("hello world!", g2d.getFontRenderContext());
But that depends on how you will get the Graphics2D
object (for example from an Image
).
但这取决于您将如何获取Graphics2D
对象(例如从Image
)。
回答by Link19
This gives the output of (137.0, 15.09375) for me. I have no idea what the units are, but it certainly looks proportionally correct and doesn't use Graphics2D directly.
这为我提供了 (137.0, 15.09375) 的输出。我不知道单位是什么,但它看起来按比例正确并且不直接使用 Graphics2D。
Font f = new Font("Ariel", Font.PLAIN, 12);
Rectangle2D r = f.getStringBounds("Hello World! Hello World!", new FontRenderContext(null, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT));
System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")");