O'Reilly logo

Java 2D Graphics by Jonathan Knudsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required