问题
my problem is that I need to save the things that I draw with java graphics as independent objects, to later recolor them, erase them indepently...
Here is my eclipse project for you to import. (The main class is the Paint class)
This is the method I use to draw:
protected void paintComponent(Graphics g) {
if (imagen == null) {
imagen = createImage(getSize().width, getSize().height);
graficos = (Graphics2D) imagen.getGraphics();
graficos.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(imagen, 0, 0, null); }
I call this function through MouseMotionListener and I get to draw. But of course this simply makes it appear and I would need to save the drawings between click and click
回答1:
The basic logic for creating an image of any component is:
Dimension d = component.getSize();
BufferedImage image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
component.print( g2d );
g2d.dispose();
ImageIO.write(image, ".jpg", new File(...));
You can check out Screen Image for a reusable class that does this for you and provides a few more features.
来源:https://stackoverflow.com/questions/64390844/how-to-save-a-drawing-made-with-java-graphics-as-a-independent-object