在Java中像素字符串长度 [英] String length in pixels in Java
问题描述
有没有一种方法来计算像素的字符串的长度,给予一定 java.awt.Font中的
对象,即不使用任何GUI组件?
这是不使用任何GUI组件?
块引用>这取决于你的意思是在这里。我假设你的意思是你想这样做没有收到一个
HeadlessException的
。最好的办法是用
的BufferedImage
。据我所知,这不会抛出HeadlessException的
:字体的字体= ...;
IMG的BufferedImage =新的BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
。FontMetrics对象FM = img.getGraphics()getFontMetrics(字体);
INT宽度= fm.stringWidth(你的字符串);除了使用这样的事情,我不认为你可以。你需要一个图形上下文,以创建一个
的FontMetrics
,并给你的字体大小的信息。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?解决方案that does not use any GUI components?
It depends on what you mean here. I'm assuming you mean you want to do it without receiving a
HeadlessException
.The best way is with a
BufferedImage
. AFAIK, this won't throw aHeadlessException
: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.这篇关于在Java中像素字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!