Displaying Graphics with Graphics2D |
AnyShape
can be used as a clipping path that restricts the portion of the drawing area that will rendered. The clipping path is part of theGraphics2D
context; to set the clip attribute, you callGraphics2D.setClip
and pass in theShape
that defines the clipping path you want to use. You can shrink the clipping path by calling theclip
method and passing in anotherShape
; the clip is set to the intersection of the current clip and the specifiedShape
.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 thenclip
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 isClipImage.html
.
Displaying Graphics with Graphics2D |