How to disable java.awt.Graphics.fillRect(int x, int y, int width, int height)'s effect?

前端 未结 3 779
一生所求
一生所求 2020-12-21 18:13

It\'s the original image: \"enter

I use java.awt.Graphics.fillRect(int x, int y, int

3条回答
  •  死守一世寂寞
    2020-12-21 19:03

    Yes this is easily doable. The problem is that any draw operation is destructive, what you see is what you get, the information that was painted upon is lost.

    Something like this where you store a subimage, do your paint operation then draw the subimage back on top.

    public class Q23709070 {
    
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            Panel p = new Panel();
    
            frame.getContentPane().add(p);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        static class Panel extends JPanel {
            int w = 400;
            int h = 400;
            int x = 100;
            int y = 100;
            BufferedImage img;
            BufferedImage subImg;
            BufferedImage save;
    
            public Panel() {
                try {
                    img = ImageIO.read(getClass().getResourceAsStream("0qzCf.jpg"));
                } catch (IOException e) {
                }
                subImg = img.getSubimage(x, y, w, h);
    
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                Color g2dColor = g2d.getColor();
                Color fillColor = new Color(0, 0, 0, 100);
    
                g2d.drawImage(img, 0, 0, null);
                g2d.setColor(fillColor);
                g2d.fillRect(0, 0, img.getWidth(), img.getHeight());
                g2d.drawImage(subImg, x, y, null);
                g2d.setColor(g2dColor);
    
                if (save == null) {
                    save = new BufferedImage(img.getWidth(), img.getHeight(),
                            img.getType());
                    this.paint(save.getGraphics());
                    try {
                        ImageIO.write(save, "jpg", new File("save.jpg"));
                    } catch (IOException e) {
                    }
                }
    
            }
    
            @Override
            @Transient
            public Dimension getPreferredSize() {
                return new Dimension(img.getWidth(), img.getHeight());
            }
        }
    }
    

    Rendering enter image description here

提交回复
热议问题