旋转图像是非三角的,即使是90度也需要一定的工作量。
所以,基于几乎所有关于旋转图像的问题,我会从…
public BufferedImage rotate(BufferedImage image, Double degrees) {
// Calculate the new size of the image based on the angle of rotaion
double radians = Math.toRadians(degrees);
double sin = Math.abs(Math.sin(radians));
double cos = Math.abs(Math.cos(radians));
int newWidth = (int) Math.round(image.getWidth() * cos + image.getHeight() * sin);
int newHeight = (int) Math.round(image.getWidth() * sin + image.getHeight() * cos);
// Create a new image
BufferedImage rotate = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotate.createGraphics();
// Calculate the "anchor" point around which the image will be rotated
int x = (newWidth - image.getWidth()) / 2;
int y = (newHeight - image.getHeight()) / 2;
// Transform the origin point around the anchor point
AffineTransform at = new AffineTransform();
at.setToRotation(radians, x + (image.getWidth() / 2), y + (image.getHeight() / 2));
at.translate(x, y);
g2d.setTransform(at);
// Paint the originl image
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return rotate;
}
当您只旋转90度时,这将计算新图像所需的大小,以便能够以任何角度绘制旋转的图像。
然后它只是利用
AffineTransform
要操纵绘画发生的原点-使用这个,你会做很多。
然后,我加载图像,旋转它们并显示它们…
try {
BufferedImage original = ImageIO.read(getClass().getResource("domino.jpg"));
BufferedImage rotated90 = rotate(original, 90.0d);
BufferedImage rotatedMinus90 = rotate(original, -90.0d);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(original)));
panel.add(new JLabel(new ImageIcon(rotated90)));
panel.add(new JLabel(new ImageIcon(rotatedMinus90)));
JOptionPane.showMessageDialog(null, panel, null, JOptionPane.PLAIN_MESSAGE, null);
} catch (IOException ex) {
ex.printStackTrace();
}
我更喜欢用
ImageIO
加载图像,因为它抛出
IOException
当事情出错时,宁愿默默地失败
ImageIcon
.
您还应该将资源嵌入到应用程序的上下文中,这使得在运行时加载它们更加容易。取决于IDE和项目的设置方式,您的设置方式将发生变化,但在“大多数”情况下,您应该能够将资源直接添加到源目录(最好是子目录中),并且IDE将使您可以使用它并在导出项目时对其进行打包