5.1. Transforming

A single class, java.awt.geom.AffineTransform, represents transformations in the 2D API. An affine transformation is one in which parallel lines are still parallel after being transformed. Affine transformations are based on matrix math, but you don't have to know anything about the math to use the AffineTransform class.

Graphics2D has an internal AffineTransform that it applies to graphics objects as they are rendered. You can set or modify this transformation with the following methods in the Graphics2D class:

public abstract void setTransform(AffineTransform Tx)

This method sets the current transformation of this Graphics2D.

public abstract void transform(AffineTransform Tx)

Use this method to modify this Graphics2D's current transformation with the supplied AffineTransform.

Graphics2D also includes convenience methods for performing simple transformations on User Space. These are described in a later section.

In general, it's a good idea to modify the existing transformation rather than replacing it. If you're drawing inside a Component, the Graphics2D that is passed to the Component's paint() method is already set up with a default transformation that places the origin at the upper left corner of the Component's drawing surface. If you replace this transformation using setTransform(), you may not get the results you expected. Instead, use transform() to modify the current transformation.

A single instance of AffineTransform can represent more than one ...

Get Java 2D Graphics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.