Hi!
I have several 55 x 55 px png-pictures, which need to be rotated by 0, 90, 180 or 270°. I tried the following but in that cases the pictures were not on their correct positions anymore.
Thanks.

// Import the basic graphics classes.
import java.awt.*;
import javax.swing.*;

/**
 * Simple program that loads, rotates and displays an image.
 * Uses the file Duke_Blocks.gif, which should be in
 * the same directory.
 * 
 * @author MAG
 * @version 20Feb2009
 */

public class RotateImage extends JPanel{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    // Declare an Image object for us to use.
    Image image;

    // Create a constructor method
    public RotateImage(){
       super();
       // Load an image to play with.
       image = Toolkit.getDefaultToolkit().getImage("abc.png");
    }

    public void paintComponent(Graphics g){
         Graphics2D g2d=(Graphics2D)g; // Create a Java2D version of g.
         g2d.translate(55/2d, 55/2d); // Translate the center of our coordinates.
         g2d.rotate(Math.toRadians(360));  // Rotate the image by 1 radian.
         g2d.drawImage(image, 0, 0, 55, 55, this);
    }

    public static void main(String arg[]){
       JFrame frame = new JFrame("RotateImage");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setSize(600,400);

       RotateImage panel = new RotateImage();
       frame.setContentPane(panel);  
       frame.setVisible(true);  
    }
}

Recommended Answers

All 4 Replies

How much rotation do you see with the posted code? I can't see any.

 g2d.rotate(Math.toRadians(0));
 g2d.rotate(Math.toRadians(90));
 g2d.rotate(Math.toRadians(180));
 g2d.rotate(Math.toRadians(270));
 g2d.rotate(Math.toRadians(360));

Yes, you're right, I just tried some different numbers, but the position is each time different.

Yes it requires changes to the x,y location values also. Try some experimenting. The numbers can be negative as well.

Thanks, that was a good idea ;)
// 0: 0, 0
// 90: 55, 0
// 180: 55, 55
// 270: 0, 55
// 360: 0, 0

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.