2011-02-24 81 views
1

當用戶在圖像頂部繪製矩形時,我想要爲所有圖像旋轉角度(90,180,270,360)提前查找所有旋轉的矩形。使用Swing在圖像上旋轉矩形

根據Java API,我可以繼續調用Graphics2D rotate()方法。然後我可以使用這個Graphics2D轉換器來獲得旋轉的Rectangle。

這適用於第一次輪換(1.5708)呼叫。我得到正確的矩形點。之後的所有其他調用在使用Transformer後返回錯誤的Rectangle Point。

我想我的問題是Graphics2D translate(x,y)。我不明白如何使用它。

任何人都知道如何修復我的代碼,以便它在每次旋轉後都會返回正確的Rectangle?

謝謝。

public void rotateRectangles(BufferedImage bim,int width,int height,Rectangle rect){ 
    BufferedImage bim = new BufferedImage(height, width,BufferedImage.TYPE_INT_RGB); 
    Graphics2D g2d = (Graphics2D) (bufferedImage.createGraphics()); 
    g2d.translate(bufferedImage.getHeight(),0); 

    //Get Rectangle for 90 degree image rotation. This always good. 
    g2d.rotate(1.5708); 
    Shape shape = g2d.getTransform().createTransformedShape(rect); 
    Rectangle rotatedRect = shape.getBounds(); 
    System.out.println("rotated rectangle at 90 degrees. Point x="+rotatedRect.x+" y="+rotatedRect.y); 


    //Get Rectangle for 180 degree image rotation. Getting wrong rotatedRect. 
    g2d.rotate(1.5708); 
    shape = g2d.getTransform().createTransformedShape(rect); 
    rotatedRect = shape.getBounds(); 
    System.out.println("rotated rectangle at 180 degrees. Point x="+rotatedRect.x+" y="+rotatedRect.y); 


    //Get Rectangle for 270 degree image rotation. Getting wrong rotatedRect. 
    g2d.rotate(1.5708); 
    shape = g2d.getTransform().createTransformedShape(rect); 
    rotatedRect = shape.getBounds(); 
    System.out.println("rotated rectangle at 270 degrees. Point x="+rotatedRect.x+" y="+rotatedRect.y); 


    //Get Rectangle for 360 degree image rotation.Getting wrong rotatedRect. 
    g2d.rotate(1.5708); 
    shape = g2d.getTransform().createTransformedShape(rect); 
    rotatedRect = shape.getBounds(); 
    System.out.println("rotated rectangle at 360 degrees. Point x="+rotatedRect.x+" y="+rotatedRect.y);   

}

謝謝。

+0

什麼是回報,你在期待什麼? – jzd 2011-02-24 17:40:00

+0

我需要一個實際的Rectangle對象,用於所有90,180,270,360度。只是試圖提前爲所有旋轉創建矩形。 – Marquinio 2011-02-24 17:59:04

+0

是的,但第二次輸出的代碼是什麼,以及您特別期待什麼。 – jzd 2011-02-24 18:09:06

回答

2

而不是通過g2d.rotate()旋轉圖形上下文的仿射變換,請考慮使用,example建議。

附錄:特別注意,示例Polygon的基線最初以原點爲中心。因此,初始轉換是圍繞原點的旋轉。在你的情況下,你可以使用rotate()方法,該方法包含一個定位點,該定位點將是矩形的中心。