2016-12-17 64 views
0

我目前正在製作一個需要旋轉圖像的遊戲。爲了旋轉它,我使用下面的代碼。用不同顏色替換旋轉圖像的角落

public ManipulableImage rotate(double degrees){ 
    BufferedImage rotatedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); 
    Graphics2D g = rotatedImage.createGraphics(); 
    g.rotate(Math.toRadians(degrees), image.getWidth()/2, image.getHeight()/2); 
    /* 
    ManipulableImage is a custom class that makes it easier to manipulate 
    an image code wise. 
    */ 
    g.drawImage(image, 0, 0, null); 
    return new ManipulableImage(rotatedImage, true).replace(0, -1); 
} 

該代碼確實旋轉圖像,但它留下的角落應該是透明的黑色。我的渲染器將rgb值-1識別爲透明值,並且在該值存在時不會更改像素。所以,我想將角的rgb值從0(黑色)更改爲-1(透明)。

唯一的問題是,我不能簡單地遍歷圖像並替換黑色像素,因爲原始圖像中有其他像素是黑色的。所以我的問題是,我如何只更換由旋轉創建的黑色像素。

(抱歉,我不能提供圖像的例子,我不知道如何使用這臺電腦截圖)

+0

您可以嘗試製作一種算法,給定一個點,搜索所有具有相同顏色的鄰居,然後迭代這些鄰居。由於角落是黑色的,如果你在四個角落開始迭代,它應該得到所有4個黑色區域。 – ebeneditos

+0

這也不完美,因爲圖像邊緣可能有黑色像素。 –

+0

對,是新圖像邊緣上旋轉的原始圖像的角? – ebeneditos

回答

1

圖形對象沒有上下文來爲這些新像素着色,所以它只是將它們染成黑色。

BufferedImage rotatedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); 

您應該使用下面這樣的BufferedImage支持透明度:

BufferedImage.TYPE_INT_ARGB 

然後在畫代碼,你可以使用:

g.setColor(new Color(0, 0, 0, 0)); 
g.fillRect(0, 0, image.getWidth(), image.getHeight()); 
g.rotate(...); 
g.drawImage(...); 
0

如果我理解正確的話,您有以下旋轉:

enter image description here

綠色單元格是原始圖像旋轉,而白色單元格是您要刪除的區域。從給出的旋轉和程度,就可以知道紅細胞的座標,因此,刪除符合條件的單元格:

(x_coord <= x1 and y_coord > x_coord * y1/x1) /* Top Left */ or 
(x_coord >= x2 and y_coord > x_coord * y2/x2) /* Top Right */ or 
(x_coord >= x3 and y_coord < x_coord * y3/x3) /* Bottom Right */ or 
(x_coord <= x4 and y_coord < x_coord * y4/x4) /* Bottom Left */ 

希望這有助於!

+0

是的,我猜這些條件會稍微改變其他角落。謝謝。這應該很好! –

+0

是的!剛剛編輯了其他條件! – ebeneditos