Previous | Next | Trail Map | 2D Graphics | Displaying Graphics with Graphics2D

Clipping the Drawing Region

Any Shape can be used as a clipping path that restricts the portion of the drawing area that will rendered. The clipping path is part of the Graphics2D context; to set the clip attribute, you call Graphics2D.setClip and pass in the Shape that defines the clipping path you want to use. You can shrink the clipping path by calling the clip method and passing in another Shape; the clip is set to the intersection of the current clip and the specified Shape.

Example: ClipImage

This example animates a clipping path to reveal different portions of an image.

The clipping path is defined by the intersection of an ellipse and a rectangle whose dimensions are set randomly. The ellipse is passed to the setClip method, and then clip is called to set the clipping path to the intersection of the ellipse and the rectangle.

private Ellipse2D ellipse = new Ellipse2D.Float();
private Rectangle2D rect = new Rectangle2D.Float();
...
ellipse.setFrame(x, y, ew, eh);
g2.setClip(ellipse);
rect.setRect(x+5, y+5, ew-10, eh-10);
g2.clip(rect);

The complete code for this program in in ClipImage.java and an HTML file that includes the applet is ClipImage.html.


Previous | Next | Trail Map | 2D Graphics | Displaying Graphics with Graphics2D