2015-08-26 25 views
2

好日子繪製圖像的透明度,上BufferStrategy中

我試着畫上BufferStrategy的圖片,其Graphics。該圖片具有透明背景,如果我在屏幕上繪製它,透明區域會變成黑色。

Blue example

藍色的是我要畫的圖像,但沒有黑色部分(在原始圖片它們不存在)。

這就是我畫的圖片:

BufferedImage image = loadImage(path); 

g.drawImage(image, x, y, null); 

public BufferedImage loadImage(String path) { 

     ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource(path)); 

     BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB); 

     Graphics g = image.createGraphics(); 

     icon.paintIcon(null, g, 0, 0); 
     g.dispose(); 

     return image; 

} 
+0

源代碼解釋你的問題詳細,你也想作爲一個什麼提供圖片結果是一個好的解決方案。 – Programmer

+0

@Programmer我更新了它:) – Neatoro

+1

你的圖片沒有alpha通道。使用BufferedImage.TYPE_INT_RGBA代替 – Andreas

回答

1

從安地列斯的評論是正確的,但應該是ARGB而非RGBA

要做到這一點只需更改BufferedImage.TYPE_INT_RGB在這一行:

BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);

BufferedImage.TYPE_INT_ARGB

BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);


編輯迴應您的評論,下面是完整的答案:

除了創建一個BufferedImage,作爲TYPE_INT_ARGB你還需要使用的Graphics2D這樣對的AlphaComposite SRC_OVER適用於您的緩衝圖像:

public static BufferedImage loadImage(String path) 
{ 
    ImageIcon icon = new ImageIcon(path); 

    //using TYPE_INT_ARGB 
    BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);  

    //changed to G2D change here 
    Graphics2D g2d = image.createGraphics(); 
    //get alpha 
    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER); 
    //set alpha 
    g2d.setComposite(ac); 

    icon.paintIcon(null, g2d, 0, 0); 
    g2d.dispose(); 

    return image; 
} 
+0

我試過了,但沒有變化,仍然是黑色背景-.- – Neatoro

+0

您還需要使用Graphics2D將AlphaComposite'SRC_OVER'應用於緩衝圖像。看到我的編輯上面的工作代碼。 – sorifiend