Java Reference
In-Depth Information
Next on our affine tour - how we can create completely new
AffineTransform
objects.
Creating AffineTransform Objects
Of course, there are constructors for
AffineTransform
objects: the default 'identity' constructor and
a number of other constructors, but we don't have space to go into them here. The easiest way to create
transform objects is to call a
static
member of the
AffineTransform
class. There are four static
methods corresponding to the four kinds of transform that we discussed earlier:
getTranslateInstance(double deltaX, double deltaY)
getRotateInstance(double angle)
getScaleInstance(double scaleX, double scaleY)
getShearInstance(double shearX, double shearY)
Each of these returns an
AffineTransform
object containing the transform that you specify by the
arguments. To create a transform to rotate the user space by 90 degrees, you could write:
AffineTransform at = AffineTransform.getRotateInstance(Math.PI/2);
Once you have an
AffineTransform
object, you can apply it to a graphics context by passing it as an
argument to the
setTransform()
method. It has another use too: you can use it to transform a
Shape
object. The
createTransformedShape()
method for the
AffineTransform
object does
this. Suppose we define a
Rectangle
object with the statement:
Rectangle rect = new Rectangle(10, 10, 100, 50);
We now have a rectangle that is 100 wide by 50 high, at position 10,10. We can create a transform
object with the statement:
AffineTransform at = getTranslateInstance(25, 30);
This is a translation in
x
of 25, and a translation in
y
of 30. We can create a new
Shape
from our
rectangle with the statement:
Shape transRect = at.createTransformedShape(rect);
Our new
transRect
object will look the same as the original rectangle but translated by 25 in
x
and 30
in
y
, so its top-left corner will now be at (35, 40).