AnyShapeobject can be used as a clipping path that restricts the portion of the drawing area that will rendered. The clipping path is part of theGraphics2Dcontext; to set the clip attribute, you callGraphics2D.setClipand pass in theShapethat defines the clipping path you want to use. You can shrink the clipping path by calling theclipmethod and passing in anotherShape; the clip is set to the intersection of the current clip and the specifiedShape.
This example animates a clipping path to reveal different portions of an image.
Note: If you don't see the applet running above, you need to install Java Plug-in, which happens automatically when you install the Java(TM) SE JRE or JDK. This applet requires JDK 6 or later. You can find more information on the Java Plug-in home page.
ClipImage.javacontains the complete code for this applet. The applet requires theclouds.jpgimage file.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
setClipmethod, and thenclipis 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);
A clipping area can also be created from a text string. The following example creates aTextLayoutwith the string The Starry Night. Then, it gets the outline of theTextLayout. TheTextLayout.getOutlinemethod returns aShapeobject and aRectangleis created from the bounds of thisShapeobject. The bounds contains all the pixels the layout can draw. The color in the graphics context is set to blue and the outline shape is drawn, as illustrated by the following image and code snippet.FontRenderContext frc = g2.getFontRenderContext(); Font f = new Font("Helvetica", 1, w/10); String s = new String("The Starry Night"); TextLayout tl = new TextLayout(s, f, frc); AffineTransform transform = new AffineTransform(); Shape outline = textTl.getOutline(null); Rectangle r = outline.getBounds(); transform = g2.getTransform(); transform.translate(w/2-(r.width/2), h/2+(r.height/2)); g2.transform(transform); g2.setColor(Color.blue); g2.draw(outline);Next, a clipping area is set on the graphics context using the
Shapeobject created fromgetOutline. Thestarry.gifimage, which is Van Gogh's famous painting, The Starry Night, is drawn into this clipping area starting at the lower left corner of theRectangleobject.
g2.setClip(outline); g2.drawImage(img, r.x, r.y, r.width, r.height, this);
Note: If you don't see the applet running above, you need to install Java Plug-in, which happens automatically when you install the Java(TM) SE JRE or JDK. This applet requires JDK 6 or later. You can find more information on the Java Plug-in home page.
Starry.javacontains the complete code for this program. This applet requires theStarry.gifimage file.