Clipping is restricting of drawing to a certain area. : Clip « 2D Graphics GUI « Java






Clipping is restricting of drawing to a certain area.

Clipping is restricting of drawing to a certain area.
    

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Clipping extends JPanel implements ActionListener {
  int x = 8, y = 8, radius = 90;
  Timer timer;
  Image image = new ImageIcon("yourImage.png").getImage();
  double delta[] = { 3, 3 };

  public Clipping() {
    timer = new Timer(15, this);
    timer.start();
  }

  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setClip(new Ellipse2D.Double(x, y, radius, radius));
    g2d.drawImage(image, 5, 5, null);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new Clipping());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
    int w = 400;
    int h = 400;

    if (x < 0) {
      delta[0] = Math.random() % 4 + 5;
    } else if (x > w - radius) {
      delta[0] = -(Math.random() % 4 + 5);
    }

    if (y < 0) {
      delta[1] = Math.random() % 4 + 5;
    } else if (y > h - radius) {
      delta[1] = -(Math.random() % 4 + 5);
    }

    x += delta[0];
    y += delta[1];

    repaint();
  }
}

   
    
    
    
  








Related examples in the same category

1.Clip the areaClip the area
2.Clip ImageClip Image
3.Clip another areaClip another area
4.Setting the Clipping Area with a Shape
5.Copy Area Performance
6.set Clip and get Clip
7.Represents a clipping rectangle in a prefuse DisplayRepresents a clipping rectangle in a prefuse Display
8.Clips the specified line to the given rectangle.