简体   繁体   中英

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

I have a JPanel which displays a graph using the Graphic2D. This works fine. I now want to be able to save the graph to a file. So far the only way I can get this to work is create a BufferedImage and everything I write to the JPanels Graphic2D object I write to the Graphic2D object belonging to the BufferedImage and then doing a PrintAll from the BufferedImage. So I have code like the following:

    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);

where g is the Graphic2D object of the JPanel and bG is the Graphic2D object of the BufferedImage

Surely this can't be the best way of doing this. Is there a way of using the Graphic2D object belonging to the JPanel to produce the Graphic2D object for the BufferedImage?

I'd extract a method, say paintGraph(Graphics2D g) that paints the graph. Then you invoke it from two locations. Once from your JPanel 's paintComponent(..) method, and once in your "saveToFile" method, using your BufferedImage 's Graphics2D instance.

You might need a Dimension as a second parameter to your method, which is either the size of your panel or your image, if your graph drawing code is resizeable.

In code:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM