Reputation: 4137
I am trying to rotate a png that is loaded in Java. The problem I have is that when I rotate the image, it also appears to also mess up the position of the image. I am rotating a 60x60 image so I would assume that rotating it would not move the image. Is there a way I can either rotate the image without moving it or a way to set the coordinates of an affine transformation?
AffineTransform identity = new AffineTransform();
gr.setColor(Color.red);
gr.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY );
AffineTransform trans = new AffineTransform();
trans.setTransform(identity);
trans.rotate( -Math.toRadians(15) );
trans.translate(-25, 220);
gr.drawImage(body.getImage(), 0, 200, null);
gr.drawImage(gun.getImage(), trans, this);
Upvotes: 0
Views: 2740
Reputation: 168845
AffineTransform
instances can be concatenated (added together) using concatenate(AffineTransform)
. The General way to rotate an image would be to.
getTranslateInstance()
).getRotateInstance()
).getTranslateInstance()
).In fact, look to the methods for
getRotateInstance(double theta,
double anchorx,
double anchory)
getRotateInstance(double vecx,
double vecy,
double anchorx,
double anchory)
Thanks to Donal Fellows for prompting me to RTM.
Upvotes: 4
Reputation: 8177
Encountered some complexity myself with rotation. Rotating 90 degrees was most problematic.
There is an API that handles this nicely and that is imgscalr.
Code:
BufferedImage rotatedPhoto = Scalr.rotate(photo, Scalr.Rotation.CW_90, null);
Didn't use imgscalr for scaling and translating, standard java.awt will do just fine there.
Since this makes a new Image photo; be sure to flush/null the old one with var.flush();
Cheers
Upvotes: 1