Narayan
Narayan

Reputation: 68

Java rotate an image in the center

How do i rotate an image in the center if itself? this code works, but it rotates the image in the top-left corner of the screen:

    AffineTransform oldtrans = new AffineTransform();
    AffineTransform trans = new AffineTransform();

    trans.setToIdentity();
    trans.rotate(Math.toRadians(angle));
    trans.translate(_x-(width/2), _y-(height/2));
    g.setTransform(trans);
    g.drawImage(this.getImage(), (int)_x, (int)_y, (int)width, (int)height, null);
    trans.setToIdentity();
    g.setTransform(oldtrans);

Please help!!!

Upvotes: 4

Views: 8167

Answers (2)

Hidde
Hidde

Reputation: 11913

You should give two more arguments in your rotate() call:

affineTransform.rotate(Math.toRadians(angle), m_imageWidth/2, m_imageHeight/2); 

Upvotes: 9

Jaco Van Niekerk
Jaco Van Niekerk

Reputation: 4182

You're halfway there, literally. What you have to do is two translations. Something along the lines of:

  1. Translate the image to its centre (tanslate(x-width/2, y-width/2).
  2. Rotate the image by angle radians (like you have).
  3. Translate the image back to its original position (tanslate(x+width/2, y+width/2).

Hope this works for you.

Upvotes: 4

Related Questions