Search code examples
javagraphicslinear-algebrajava-2daffinetransform

Rotation and Scaling -- How to do both and get the right result?


I've got a set of Java2D calls that draw vectors on a graphics context. I'd like for the image to be doubled in size and then rotated 90 degrees.

I'm using the following code to do this:

Graphics2D g2 = // ... get graphics 2d somehow ...
AffineTransform oldTransform = g2.getTransform();
AffineTransform newTransform = (AffineTransform)oldTransform.clone();
newTransform.concatenate(AffineTransform.getTranslateInstance(x1, x2));
newTransform.concatenate(AffineTransform.getScaleInstance((double)newW/(double)iconW, (double)newH/(double)iconH));
newTransform.concatenate(AffineTransform.getRotateInstance(Math.toRadians(rotationAngle), (double)iconW/2.0d, (double)iconH/2.0d));
// ... do my drawing ...

This rotates and scales, however, the scale isn't applied the way I would like. It is as if it is rotated before scaling, thus making the image wider on the wrong axis.

Is there a better way to do this?


Solution

  • I believe those transforms are implemented like a stack - so the last transform is performed first. Try reversing the order of the rotate and scale transformations and you should get what you are looking for.

    newTransform.concatenate(AffineTransform.getTranslateInstance(x1, x2));
    newTransform.concatenate(AffineTransform.getRotateInstance(Math.toRadians(rotationAngle), (double)iconW/2.0d, (double)iconH/2.0d));
    newTransform.concatenate(AffineTransform.getScaleInstance((double)newW/(double)iconW, (double)newH/(double)iconH));