The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: 2D Graphics
Lesson: Displaying Graphics with Graphics2D

Transforming Shapes, Text, and Images

You can modify the transform attribute in the Graphics2D context to move, rotate, scale, and shear graphics primitives when they are rendered. The transform attribute is defined by an instance of AffineTransform. (An affine transform is a transformation such as translate, rotate, scale, or shear in which parallel lines remain parallel even after being transformed.)

Graphics2D provides several methods for changing the transform attribute. You can construct a new AffineTransform and change the Graphics2D transform attribute by calling setTransform.

AffineTransform defines the following factory methods to make it easier to construct new transforms:

Alternatively you can use one of the Graphics2D transformation methods to modify the current transform. When you call one of these convenience methods, the resulting transform is concatenated with the current transform and is applied during rendering:

You can also construct an AffineTransform directly and concatenate it with the current transform by calling the transform method.

The drawImage method is also overloaded to allow you to specify an AffineTransform that is applied to the image as it is rendered. Specifying a transform when you call drawImage does not affect the Graphics2D transform attribute.

Example: Transform

The following program is the same as StrokeandFill, but also allows the user to choose a transformation to apply to the selected object when it is rendered.

Click this figure to run the applet.
This is a picture of the applet's GUI. To run the applet, click the picture. The applet will appear in a new browser window.

Transform.java(in a .java source file) contains the complete code for this applet.

When a transform option is chosen, an instance of AffineTransform at is modified and is then concatenated with a translation transform that moves the Shape to the center of the window. The resulting transform is then passed to the setTransform method to set the Graphics2D transform attribute.

switch (Transform.trans.getSelectedIndex()){
case 0 : at.setToIdentity();
	 at.translate(w/2, h/2); break;
case 1 : at.rotate(Math.toRadians(45)); break;
case 2 : at.scale(0.5, 0.5); break;
case 3 : at.shear(0.5, 0.0); break;
...
AffineTransform toCenterAt = new AffineTransform();
toCenterAt.concatenate(at);
toCenterAt.translate(-(r.width/2), -(r.height/2));
g2.setTransform(toCenterAt);

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form