[英]How to rotate an imageIcon in Java
我正在用Java創建一個多米諾骨牌游戲。 我有以下代碼加載,調整大小,然后在屏幕上顯示多米諾骨牌圖像:
ImageIcon imageIcon = new ImageIcon("images\\4-4.png");
Image image = imageIcon.getImage();
Image newimg = image.getScaledInstance(60, 120, java.awt.Image.SCALE_SMOOTH);
imageIcon = new ImageIcon(newimg);
JLabel img = new JLabel(imageIcon);
img.setBounds(100, 100, 60, 120);
getContentPane().add(img);
我想做的是將圖像旋轉90度或-90度。 我已經搜索了互聯網,但是發現的示例似乎非常復雜。
知道如何旋轉圖像嗎?
順便說一句,如果您認為這不是在多米諾骨牌游戲中顯示多米諾骨牌的正確方法,請告訴我。 我是Java新手。
旋轉圖像不是很重要的事情,即使僅旋轉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會使其可供您使用,並在導出項目時打包
解決方案來自: http : //www.java2s.com/Code/Java/Advanced-Graphics/RotatingaBufferedImage.htm
AffineTransform tx = new AffineTransform();
tx.rotate(0.5, bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(tx,
AffineTransformOp.TYPE_BILINEAR);
bufferedImage = op.filter(bufferedImage, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.