Java Reference
In-Depth Information
Modifying the Transformation for a Graphics Context
Modifying the current transform for a Graphics2D object involves calling a method for the
Graphics2D object. The effect in each case is to add whatever transform you are applying to whatever
the transform did before. You can add each of the four kinds of transforms that we discussed before
using the following methods defined in the Graphics2D class:
translate(double deltaX, double deltaY)
translate(int deltaX, int deltaY)
rotate(double angle)
rotate(double angle, double deltaX, double deltaY)
scale(double scaleX, double scaleY)
shear(double shearX, double shearY)
Each of these adds or concatenates the transform specified to the existing transform object for a
Graphics2D object. Therefore you can cause a translation of the coordinate system followed by a
rotation about the new origin position with the statements:
g2D.translate(5, 10); // Translate the origin
g2D.rotate(Math.PI/3); // Clockwise rotation 60 degrees
g2D.draw(line); // Draw in translate and rotated space
Of course, you can apply more than two transforms to the user coordinate system - as many as you like.
However, it is important to note that the order in which you apply the transforms matters. To see why,
look at the example below.
Device Coordinates
Device Coordinates
x
x
y
y
Translate by 0,deltaY
Rotate -pi/4
Rotate -pi/4
Translate by 0,deltaY
This shows just two transforms in effect, but it should be clear that the sequence in which they are applied
makes a big difference. This is because the second transform is always applied relative to the new position of
the coordinate system after the first transform has been applied. If you need more convincing that the order
in which you apply transforms matters, you can apply some transforms to yourself. Stand with your back to
any wall in the room. Now apply a translation - take three steps forward. Next apply a rotation - turn
through 45 degrees clockwise. Make a mental note of where you are. If you now go back and stand with your
back to the wall in the original position and first turn through 45 degrees before you take the three steps
forward, you will clearly be in quite a different place in the room from the first time around.
Search WWH ::




Custom Search