1

我想用 Java 创建一个 PNG 图像。在这张图片中,我想显示一些随机文本。Normaly 我会创建这样的图片:

BufferedImage bi = new BufferedImage(300,300,BufferedImage.TYPE_INT_ARGB);
bi.getGraphics().drawString("Hello world", 0, 0);
ImageIO.write(bi, "png", File.createTempFile("out", ".png"));

我知道我可以使用以下代码计算字符串长度:

bi.getGraphics().getFontMetrics().stringWidth("Hello world");

但要执行此操作,我需要一个图形对象(我从 BufferedImage 中获取)。所以我必须先声明 BufferedImage,然后才能使用 stringWidth。

结果是,图像比需要的大得多。

我看到的唯一方法是创建一个“虚拟 BufferedImage”。所以我可以计算所需的宽度和高度,然后我可以创建一个适合的 BufferedImage。

我找不到更好的解决方案,但也许有人可以帮助我。

非常感谢。

4

1 回答 1

0

抱歉,很着急,但请考虑以下测试:

public static void main(String[] args) {
    Font font = Font.decode(Font.MONOSPACED);

    Rectangle2D bounds;
    String str = "Hello World";

    BufferedImage dummy = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);

    FontRenderContext context = new FontRenderContext(new AffineTransform(), true, true);
    bounds = font.getStringBounds(str, context);
    System.err.println("bounds: " + bounds);

    bounds = font.getStringBounds(str, dummy.createGraphics().getFontRenderContext());
    System.err.println("bounds: " + bounds);

    Graphics2D graphics = dummy.createGraphics();
    FontMetrics fontMetrics = graphics.getFontMetrics(font);
    bounds = fontMetrics.getStringBounds(str, graphics);
    System.err.println("bounds: " + bounds);
}

输出:

bounds: java.awt.geom.Rectangle2D$Float[x=0.0,y=-12.064453,w=79.21289,h=15.667969]
bounds: java.awt.geom.Rectangle2D$Float[x=0.0,y=-12.064453,w=77.0,h=15.667969]
bounds: java.awt.geom.Rectangle2D$Float[x=0.0,y=-12.064453,w=77.0,h=15.667969]

因此,似乎仅创建一个 dummy 最有可能获得所需的结果(文档还指出创建一个FontRenderContext可能会产生意外/未定义的结果)。

于 2014-02-04T16:39:01.120 回答