Inside clipping with Java Graphics

后端 未结 2 1073
时光说笑
时光说笑 2021-01-04 19:57

I need to draw a line using java.awt.Graphics, but only the portion of the line that lies outside of a rectangle should be rendered.

Is it possible to use the Graphi

2条回答
  •  一生所求
    2021-01-04 20:20

    You need to use the Area class. This example will demonstrate how to do what you ask:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Area;
    import java.awt.geom.Rectangle2D;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    
    public class Test extends JPanel {
    
        public static void main(String[] args) {
            JFrame f = new JFrame();
            Test t = new Test();
            f.getContentPane().setLayout(new BorderLayout());
            f.getContentPane().add(t,BorderLayout.CENTER);
            f.pack();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
        }
    
        public Test() {
            setPreferredSize(new Dimension(300, 300));
        }
    
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g.create();
            Rectangle2D rectangleNotToDrawIn = new Rectangle2D.Double(100, 100, 20, 30);
            Area outside = calculateRectOutside(rectangleNotToDrawIn);
            g2.setPaint(Color.white);
            g2.fillRect(0, 0, getWidth(), getHeight());
            g2.setPaint(Color.black);
            g2.setClip(outside);
            g2.drawLine(0, 0, getWidth(), getHeight());
    
        }
    
    
        private Area calculateRectOutside(Rectangle2D r) {
            Area outside = new Area(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
            outside.subtract(new Area(r));
            return outside;
        }
    
    }
    

提交回复
热议问题