Rotating image using Java 2D AffineTransform class
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import javax.swing.JPanel;
class ImagePanel extends JPanel {
int offset = 5;
private Image image;
private int angle;
private int w, h;
private AffineTransform transform;
public ImagePanel(Image i) {
image = i;
w = image.getWidth(this);
h = image.getHeight(this);
transform = new AffineTransform();
}
public void paintComponent(Graphics grp) {
Rectangle rect = this.getBounds();
Graphics2D g2d = (Graphics2D) grp;
transform.setToTranslation((rect.width - w) / 2,
(rect.height - h) / 2);
transform.rotate(Math.toRadians(angle), w / 2,
h / 2);
g2d.drawImage(image, transform, this);
}
public void rotate() {
angle -= offset;
if (angle <= 0) {
angle = 360;
}
repaint();
}
}
Related examples in the same category