Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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
.
This example animates a clipping path to reveal different portions of an image.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.
ClipImage.java
contains the complete code for this applet. The applet requires theclouds.jpg
image 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
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);
A clipping area can also be created from a text string. The following example creates aTextLayout
with the string The Starry Night. Then, it gets the outline of theTextLayout
. TheTextLayout.getOutline
method returns aShape
object and aRectangle
is created from the bounds of thisShape
object. 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
Shape
object created fromgetOutline
. Thestarry.gif
image, which is Van Gogh's famous painting, The Starry Night, is drawn into this clipping area starting at the lower left corner of theRectangle
object.
g2.setClip(outline); g2.drawImage(img, r.x, r.y, r.width, r.height, this);
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.
Starry.java
contains the complete code for this program. This applet requires theStarry.gif
image file.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.