以下代码正常运行,但我无法理解某些细节。有人可以帮我理解AffineTransform
如何旋转图像吗?
package pks;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class rotate {
public static void main(String[] args) {
new rotate();
}
public rotate() {
EventQueue.invokeLater(new Runnable() {
public void run() {
final RotationPane rotationPane = new RotationPane(); // initilize object of RotationPane class
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(rotationPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class RotationPane extends JPanel {
private BufferedImage img;
private BufferedImage rotated;
private double angle;
public RotationPane() {
try {
img = ImageIO.read(new File("C:\\Users\\pardeep\\Desktop\\tomb1.jpg")); // path of the image to be rotated
setAngle(45);
}
catch (IOException ex) {
}
}
public void setAngle(double angle) {
this.angle = angle;
// Using Affine transform we will calculate the new values
//x=vcos (theta)+wsin(theta)
//y=vcos(theta)+ wsin(theta)
double rads = Math.toRadians(angle); // calculating angle in radian
double sin = Math.abs(Math.sin(rads)), //calculating sin theta
cos = Math.abs(Math.cos(rads)); // calculating cos theta
int w = img.getWidth();
int h = img.getHeight();
int newWidth = (int) Math.floor(w * cos + h * sin); //using affine transform
int newHeight = (int) Math.floor(h * cos + w * sin);
rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotated.createGraphics(); //rotating planes.....
AffineTransform plane = new AffineTransform();
plane.translate((newWidth - w) / 2, (newHeight - h) / 2);
int x=w/2;
int y=h/2;
plane.rotate(Math.toRadians(45), x, y);
g2d.setTransform(plane);
g2d.drawImage(img, 0, 0, this);
}
public Dimension getPreferredSize() {
return new Dimension(800, // setting the window size
800);
}
protected void paintComponent(Graphics g) {
// super.paintComponent(g); no need for it
if (rotated != null) { // drawing image on 2 dimentional size surface
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - rotated.getWidth()) / 2;
int y = (getHeight() - rotated.getHeight()) / 2;
g2d.drawImage(rotated, x, y, this); // overriding the method......
}
}
}
}