|
|
Displaying Graphics with Graphics2D |
You can modify the transform attribute in theGraphics2Dcontext to move, rotate, scale, and shear graphics primitives when they are rendered. The transform attribute is defined by an instance ofAffineTransform. (An affine transform is a transformation such as translate, rotate, scale, or shear in which parallel lines remain parallel even after being transformed.)
Graphics2Dprovides several methods for changing the transform attribute. You can construct a newAffineTransformand change theGraphics2Dtransform attribute by callingsetTransform.
AffineTransformdefines convenient factory methods to make it easier to construct new transforms:Alternatively, you can use one of the
Graphics2Dtransformation methods to modify the current transform. When you call one of these convenience methods, the resulting transform is concatenated with the current transform and applied during rendering.
rotate--enables you to specify an angle of rotation in radians.scale--enables you to specify a scaling factor in the x and y directions.shear--enables you to specify a shearing factor in the x and y directions.translate--enables you to specify a translation offset in the x and y directions.You can also construct an
AffineTransformdirectly and concatenate it with the current transform by calling thetransformmethod.The
drawImagemethod is also overloaded to allow you to specify anAffineTransformthat is applied to the image as it is rendered. Specifying a transform when you calldrawImagedoes not affect theGraphics2Dtransform attribute.Example: Transform
The following program,
Transformis the same asStrokeandFill, except that it also allows the user to select a transformation to apply to the selected object when it is rendered.When a transform option is selected, an instance ofAffineTransformat is modified and then concatenated with a translation transform that moves theShapeto the center of the window. The resulting transform is then passed to thesetTransformmethod to set theGraphics2Dtransform attribute:Here's the complete code for this programswitch (Transform.trans.getSelectedIndex()){ case 0 : at.setToIdentity(); at.translate(w/2, h/2); break; case 1 : at.rotate(Math.toRadians(45)); break; case 2 : at.scale(0.5, 0.5); break; case 3 : at.shear(0.5, 0.0); break; ... AffineTransform toCenterAt = new AffineTransform(); toCenterAt.concatenate(at); toCenterAt.translate(-(r.width/2), -(r.height/2)); g2.setTransform(toCenterAt);Transform.javaand an HTML file that includes the appletTransform.html.
![]()
Displaying Graphics with Graphics2D