Java中的像素中的字符串长度



是否有一种方法可以计算出一个不使用任何GUI组件的java.awt.Font对象中的像素中的字符串长度?

不使用任何GUI组件?

这取决于您的意思。我假设您的意思是您想在不收到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");

除了使用类似的东西外,我认为您不能。您需要一个图形上下文才能创建FontMetrics并为您提供字体大小信息。

您可以使用Graphics2D对象获取字体界(包括宽度):

Graphics2D g2d = ...
Font font = ...
Rectangle2D f = font.getStringBounds("hello world!", g2d.getFontRenderContext());

,但这取决于您将如何获得Graphics2D对象(例如Image)。

这给我提供了(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() + ")"); 

我需要在调用PaintComponent之前获得字符串的长度和宽度,以便我可以将封闭面板大小缩小到文本尺寸。这些技术都没有提供足够的宽度,我没有可用的图形对象。我通过将字体设置为" Monoperaced"。

来解决问题。

最新更新