有没有办法复制 JPanel Graphics2D 实例来为 BufferedImage 制作 Graphic 2D?

Is there a way of copying a JPanel's Graphic2D instance to make a Graphic2D for a BufferedImage?

我有一个使用 Graphic2D 显示图形的 JPanel。这很好用。我现在希望能够将图形保存到文件中。到目前为止,我能让它工作的唯一方法是创建一个 BufferedImage,然后将我写入 JPanels Graphic2D 对象的所有内容写入属于 BufferedImage 的 Graphic2D 对象,然后从 BufferedImage 执行 PrintAll。 所以我有如下代码:

    g.setFont(g.getFont().deriveFont(fontSize));
    g.drawString(text, xPos, yPos);
    g.setFont(saveFont);
    bG.setFont(g.getFont().deriveFont(fontSize));
    bG.drawString(text, xPos, yPos);
    bG.setFont(saveFont);

其中 g 是 JPanel 的 Graphic2D 对象 bG 是 BufferedImage

的 Graphic2D 对象

当然这不是最好的方法。有没有办法使用属于 JPanel 的 Graphic2D 对象来为 BufferedImage 生成 Graphic2D 对象?

我会提取一个绘制图形的方法,比如 paintGraph(Graphics2D g)。然后从两个位置调用它。一次来自您的 JPanelpaintComponent(..) 方法,一次在您的 "saveToFile" 方法中,使用您的 BufferedImageGraphics2D 实例。

您可能需要 Dimension 作为您的方法的第二个参数,如果您的图形绘制代码是可调整大小的,它可以是面板的大小或图像的大小。

在代码中:

void paintGraph(Graphics2D g, Dimension size) {
    g.setFont(g.getFont().deriveFont(fontSize));
    g.drawString(text, xPos, yPos);
    g.setFont(saveFont);
    // ...etc
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    paintGraph((Graphics2D) g, getSize());
}

void saveToFile(File f) {
    BufferedImage image = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = image.createGaphics();
    paintGraph(g, new Dimension(image.getWidth(), image.getHeight());
    g.dispose();

    ImageIO.write(image, "PNG", f);
}