- The Basic Java 2D Recipe
- Set the Graphics2D Context...
- ...and Render Something
- Rendering on Components
- Shape Primitives
- Graphics Stroking
- Fill Attributes and Painting
- Transparency and Compositing
- Text
- Clipping
- Coordinate Space Transformations
- Techniques for Graphical User Input
- Double Buffering
- Comprehensive Example: Kspace Visualization
- Summary
Coordinate Space Transformations
If you wanted to rotate or otherwise transform a graphics object and then redraw it, there would be two obvious ways to go. One way, which is generally impractical, is to transform each point of the graphics object and then render the transformed object. Any reasonably complicated shape would require many hundreds of transforms. The preferred way is to transform the user space, draw on it, and then render the user space to the output device.
class myCustomCanvas extends Canvas { public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.red); //setting context Rectangle2D sq1 = new Rectangle2D.Float(0.f,0.f,175.0f,175.0f); //translate user space to center g2d.translate(this.getSize().width/2, this.getSize().height/2); g2d.fill(sq1); g2d.rotate(-45); //rotate user space g2d.setColor(Color.blue); g2d.fill(sq1); } }
In Figure 3.12, a translation of user space and the blue rectangle are filled. Next, the user space is rotated -45 degrees, and the same rectangle is drawn.
Figure 3.12 Output from BasicRecipeJ2D.java after adding the preceding code snippet.
Another method available in Java 2D is the AffineTransformOp. An affine transformation is a linear matrix multiplication to a coordinate space. Many effects can be produced using an affine transformation including rotate, translate, shear, and scale. Indeed, when any graphics are rendered from user space to device space, an affine transformation is used to make the conversion. It isn't necessary to modify the transformation from user to device space, but it is interesting to note that the same method is usable for making transformations within user space. For a quick example, we will rotate the rectangle we created in the myCustomRenderMethod.