To define a clipping path:
-
Create a Shape that represents the area you want to render.
-
Call Graphics2D.setClip to use the shape as the clipping path for the Graphics2D context.
To shrink the clipping path:
-
Create a Shape that intersects the current clipping path.
-
Call clip to change the clipping path to the intersection of the current clipping path and the new Shape.
In the following example, a clipping path is created from an ellipse and then modified by calling clip.
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// The width and height of the canvas
int w = getSize().width;
int h = getSize().height;
// Create an ellipse and use it as the clipping path
Ellipse2D e = new Ellipse2D.Float(w/4.0f,h/4.0f,
w/2.0f,h/2.0f);
g2.setClip(e);
// Fill the canvas. Only the area within the clip is rendered
g2.setColor(Color.cyan);
g2.fillRect(0,0,w,h);
// Change the clipping path, setting it to the intersection of
// the current clip and a new rectangle.
Rectangle r = new Rectangle(w/4+10,h/4+10,w/2-20,h/2-20);
g2.clip(r);
// Fill the canvas. Only the area within the new clip
// is rendered
g2.setColor(Color.magenta);
g2.fillRect(0,0,w,h);
}
CONTENTS | PREV
| NEXT
Copyright © 1997-1998 Sun Microsystems, Inc. All Rights Reserved.