2012-05-31 17 views
0

我的問題很簡單:從另一個獲得一個新的旋轉imageIcon?

我有一個ImageIcon,我想獲得另一個旋轉完全旋轉* 90°次。這是方法:

private ImageIcon setRotation(ImageIcon icon, int rotation); 

我寧願不必使用外部類。 感謝

+1

[在Java Swing上旋轉JLabel或ImageIcon]的可能副本(http://stackoverflow.com/questions/4287499/rotate-jlabel-or-imageicon-on-java-swing) – oers

回答

2

獲取的BufferedImage從ImageIcon的

全部轉換爲圖像通常做的BufferedImage。您可以從ImageIcon獲取圖像,然後將其轉換爲BufferedImage的:

Image image = icon.getImage(); 
BufferedImage bi = new BufferedImage(
    image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); 
Graphics bg = bi.getGraphics(); 
bg.drawImage(im, 0, 0, null); 
bg.dispose(); 

旋轉

然後你就可以將其旋轉-90使用下面的代碼90度:

public BufferedImage rotate(BufferedImage bi, float angle) { 
    AffineTransform at = new AffineTransform(); 
    at.rotate(Math.toRadians(angle), bi.getWidth()/2.0, bi.getHeight()/2.0); 
    at.preConcatenate(findTranslation(at, bi, angle)); 

    BufferedImageOp op = 
     new AffineTransformOp(at, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); 
    return op.filter(bi, null); 
} 

private AffineTransform findTranslation(
         AffineTransform at, BufferedImage bi, float angle) { 
    Point2D p2din = null, p2dout = null; 

    if (angle > 0 && angle <= 90) { 
     p2din = new Point2D.Double(0, 0); 
    } else if (angle < 0 && angle >= -90) { 
     p2din = new Point2D.Double(bi.getWidth(), 0); 
    } 
    p2dout = at.transform(p2din, null); 
    double ytrans = p2dout.getY(); 

    if (angle > 0 && angle <= 90) { 
     p2din = new Point2D.Double(0, bi.getHeight()); 
    } else if (angle < 0 && angle >= -90) { 
     p2din = new Point2D.Double(0, 0); 
    } 
    p2dout = at.transform(p2din, null); 
    double xtrans = p2dout.getX(); 

    AffineTransform tat = new AffineTransform(); 
    tat.translate(-xtrans, -ytrans); 
    return tat; 
} 

這個偉大的工程旋轉圖像從-90到90度,它不支持更多。您可以運行AffineTransform文檔以獲取有關使用座標的更多說明。

設置BufferedImage中的ImageIcon

最後你填充變換圖像的ImageIcon:icon.setImage((Image) bi);