Java Reference
In-Depth Information
AffineTransform at = getTranslateInstance(25, 30);
The
at
object represents a translation of 25 in
x
and of 30 in
y
. You can create a new
Shape
object from
the original rectangle with the statement:
Shape transRect = at.createTransformedShape(rect);
The new
transRect
object looks the same as the original rectangle but is translated by 25 in
x
and 30 in
y
, so its top-left corner is now at (35, 40).
Figure 20-18
illustrates this operation.
However, although
transRect
looks like a rectangle, it is not a
Rectangle
object. The
createTrans-
formedShape()
method always returns a
GeneralPath
object because it has to work with any transform.
Some transformations deform a shape so the shape cannot be an instance of the original shape type. Apply-
ing a shear to a rectangle, for example, results in a shape that is no longer a rectangle. The method has to be
able to apply any transform to any
Shape
object, and returning a
GeneralPath
shape makes this possible.
Let's try some of this out with the Sketcher shape classes. At the moment, you translate the origin ex-
plicitly by calling the
translate()
method before you draw each shape or text element. Let's use an
AffineTransform
object to do the translation of the coordinate system before the element is drawn.
Translating Sketcher Elements using a Transform
Because you already draw elements at the origin, this is going to be close to trivial. Here's how you could
use a transform object in the
draw()
method for the
Element.Line
class: