Displaying Graphics with Graphics2D |
You can modify the transform attribute in theGraphics2D
context 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.)
Graphics2D
provides several methods for changing the transform attribute. You can construct a newAffineTransform
and change theGraphics2D
transform attribute by callingsetTransform
.
AffineTransform
defines the following factory methods to make it easier to construct new transforms:
getRotateInstance
getScaleInstance
getShearInstance
getTranslateInstance
Alternatively you can use one of the
Graphics2D
transformation methods to modify the current transform. When you call one of these convenience methods, the resulting transform is concatenated with the current transform and is applied during rendering:
rotate
--to specify an angle of rotation in radiansscale
--to specify a scaling factor in the x and y directionsshear
--to specify a shearing factor in the x and y directionstranslate
--to specify a translation offset in the x and y directionsYou can also construct an
AffineTransform
directly and concatenate it with the current transform by calling thetransform
method.The
drawImage
method is also overloaded to allow you to specify anAffineTransform
that is applied to the image as it is rendered. Specifying a transform when you calldrawImage
does not affect theGraphics2D
transform attribute.Example: Transform
The following program is the same asStrokeandFill
, but also allows the user to choose a transformation to apply to the selected object when it is rendered.