Java将2D图形作为参数传递 [英] Java Passing 2D Graphic as a Parameter

查看:165
本文介绍了Java将2D图形作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绘制图像然后立即保存的功能,但问题是它似乎是两次绘制,一次用于屏幕上的视图然后一次将其保存到磁盘

  public class myFrame {

public static void main(String [] args){

JFrame lv_frame = new JFrame();
//在这里设置jframe

lv_frame.add(new image());

lv_frame.setVisible(true);

}

}

类图像扩展JPanel {

public void paintComponent(Graphics graphic){

super.paintComponent(graphic);
draw(graphic);
save();

}

public void draw(图形图形){

Graphics2D graphic2D =(Graphics2D)graphic;
graphic2D.fillArc(0,0,250,250,0,90);

}

public void save(){

BufferedImage image = new BufferedImage(250,250,BufferedImage.TYPE_4BYTE_ABGR_PRE);
Graphics2D graphic2D = image.createGraphics();

try {
文件输出=新文件(file.png);

//是否可以使用我已经在这里绘制的
//而不是重新绘制的图形?
draw(graphic2D);

ImageIO.write(image,png,output);
} catch(IOException log){
System.out.println(log);
}

}

}

我有一个在gui屏幕上创建图像的函数draw和另一个将它保存到磁盘的函数save,但是save函数也调用了draw。



是否可以保存已经绘制的图像而无需重新调用绘图功能,因为它是在我的代码中完成的?

解决方案

我在






关于绘图的一些指示:




  • paintComponent(Graphics)只包含绘图代码而不包含其他内容。不要实现将代码保存到此处文件的代码。


  • 尽量不要在 paintComponent中创建新的BufferedImage(图形)。如果没有,将在每次重绘时创建一个新的BufferedImage实例。



I have a function that is drawing an image and then saving it immediately after but the problem is that it seems to be drawing it twice, once for the view on the screen and then once to save it to the disk

public class myFrame {

    public static void main(String[] args) {

        JFrame lv_frame = new JFrame();
        // setup jframe here

        lv_frame.add(new image());

        lv_frame.setVisible(true);

    }

}

class image extends JPanel {

    public void paintComponent(Graphics graphic) {

        super.paintComponent(graphic);
        draw(graphic);
        save();

    }

    public void draw(Graphics graphic) {

        Graphics2D graphic2D = (Graphics2D) graphic;
        graphic2D.fillArc(0, 0, 250, 250, 0, 90);

    }

    public void save() {

        BufferedImage image = new BufferedImage(250, 250, BufferedImage.TYPE_4BYTE_ABGR_PRE);
        Graphics2D graphic2D = image.createGraphics();

        try {
            File output = new File("file.png");

            // is it possible to use the graphic I've already
            // drawn here instead of re-drawing?
            draw(graphic2D);

            ImageIO.write(image, "png", output);
        } catch(IOException log) {
            System.out.println(log);
        }

    }

}

I have a function draw which creates the image on the gui screen and another function save which saves it to the disk but the save function is calling draw as well.

Is it possible to save the image that has already been drawn without re-calling the draw function as it is being done in my code?

解决方案

I was answering your question on Display to GUI and Save to Disk with a Single Object/Variable, however it was closed probably due to the similar nature of your question. I think there are several issues which you seemed confused with and I would like to write my solution here which also addresses your question in your duplicated post.


Is it possible to save the image that has already been drawn without re-calling the draw function as it is being done in my code?

Don't be confused between drawing an image on the Panel and saving it. The following shows a working example on saving a drawn image.

class DrawingSpace extends JPanel
{
    private BufferedImage buf;

    public DrawingSpace(){
        setPreferredSize(new Dimension(200, 200));
        buf = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
        drawOnBuffer();
    }

    public void drawOnBuffer(){
        Graphics g = buf.createGraphics();
        g.setColor(Color.BLUE);
        g.fillOval(0,0,200,200);
        g.setColor(Color.RED);
        g.fillOval(50,50,100,100);
        g.dispose();
    }

    public void saveBufferAsImage(String pathname){
        String fmt = "";
        if(!(pathname == null || pathname.equals(""))){
            fmt = pathname.substring(pathname.lastIndexOf(".")+1);
            File outputfile = new File(pathname);
            try{
                ImageIO.write(buf, fmt, outputfile);        
            }catch(IOException ioe){System.out.println("Unable to save file");}
        }       
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(buf, 0, 0, 200, 200, null); //Only for user to see
    }
}

To save an image, you not necessarily have to draw and display it in the JPanel first. Note that I created a BufferedImage called buf and I am drawing on buf. Once I have drawn onto a BufferedImage, I can simply save that image as a file (I don't have to draw it to the panel first).

Notice that I did the following:

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(buf, 0, 0, 200, 200, null); //Only for user to see
    }

g.drawImage(buf, 0, 0, 200, 200, null) will draw whatever on buf onto the JPanel. It can be deleted and the saving will still work. When I draw it on the panel, it is only for the user to see the outcome of the drawing.

To test the program:

class SaveImageRunner{
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                JFrame frame = new JFrame("Saving a buffered image");
                DrawingSpace ds = new DrawingSpace();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(ds);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                ds.saveBufferAsImage("BlueCircle.png");
            }           
        });
    }
}

Saved Image:


Some pointers on drawing:

  • paintComponent(Graphics) shall only contain codes for drawing and nothing else. Do not implement your codes for saving the image to a file inside here.

  • Try not to create a new BufferedImage in the paintComponent(Graphics). If not, a new instance of a BufferedImage will be created on every repaint.

这篇关于Java将2D图形作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆