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






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();
  }
}








16.40.Clip
16.40.1.Clip Demo
16.40.2.Clip between Rectangle and Ellipse2DClip between Rectangle and Ellipse2D
16.40.3.Animate a clipping path to reveal different portions of an imageAnimate a clipping path to reveal different portions of an image
16.40.4.A clipping area can also be created from a text string.A clipping area can also be created from a text string.
16.40.5.Setting the Clipping Area with a Shape
16.40.6.Clipping is restricting of drawing to a certain area.