Search code examples
javaimageaffinetransform

Rotating pngs in Java


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);

Solution

  • AffineTransform instances can be concatenated (added together) using concatenate(AffineTransform). The General way to rotate an image would be to.


    In fact, look to the methods for

    • getRotateInstance(double theta, double anchorx, double anchory)
      Returns a transform that rotates coordinates around an anchor point. This operation is equivalent to translating the coordinates so that the anchor point is at the origin (S1), then rotating them about the new origin (S2), and finally translating so that the intermediate origin is restored to the coordinates of the original anchor point (S3).
    • getRotateInstance(double vecx, double vecy, double anchorx, double anchory)
      Returns a transform that rotates coordinates around an anchor point accordinate (sic) to a rotation vector. All coordinates rotate about the specified anchor coordinates by the same amount. The amount of rotation is such that coordinates along the former positive X axis will subsequently align with the vector pointing from the origin to the specified vector coordinates. If both vecx and vecy are 0.0, an identity transform is returned. This operation is equivalent to calling: ...

    Thanks to Donal Fellows for prompting me to RTM.