2014-11-16 32 views
0

我正在製作一款遊戲,想要從左到右單個圖像「淡化」,圖像左側的alpha值爲1.0,右側的alpha值爲0.0。 (注意:我不希望它隨着時間的推移而改變它的樣子,比如淡入或淡出,而是從左向右逐漸消失並保持不變)。畫什麼,我想最終的結果看起來像一個嘗試以下:我可以在java中從左到右使圖像alpha淡入淡出嗎?

lll lll ll ll l l l l   l 
lll lll ll ll l l l l   l 
lll lll ll ll l l l l   l 
lll lll ll ll l l l l   l 
lll lll ll ll l l l l   l 
lll lll ll ll l l l l   l 

凡「L'S的密度代表着阿爾法

我目前用的TYPE_INT_RGB的緩衝圖像,並願如果可能的話保持不變。

是否有任何內置的java類,可以幫助我做到這一點,或者至少有一種(相對容易)的方法來做到這一點我自己,我無法弄清楚?


編輯: 我不希望有任何形式的透明邊框。我想繪製一個BufferedImage(帶有alpha漸變)到另一個BufferedImage上。

+2

一個LinearGradientPaint應該能夠做到這一點......但你可能還需要一個鋁phaComposite – MadProgrammer

+0

謝謝,我會看看那些。 – WiErD0

+0

@afzalex,我不想爲我的JFrame創建漸變,只是爲了我的BufferedImage,它被繪製在一個完全不透明的框架中 – WiErD0

回答

5

的基本思想是超過已充滿LinearGradientPaint

,所以原始圖像應用AlphaComposite面具,我們通過加載原始圖像開始...

BufferedImage original = ImageIO.read(new File("/an/image/somewhere")); 

然後,我們創建同樣大小的屏蔽圖像...

BufferedImage alphaMask = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB); 

然後,我們用LinearGradientPaint填補了掩蔽圖像...

Graphics2D g2d = alphaMask.createGraphics(); 
LinearGradientPaint lgp = new LinearGradientPaint(
     new Point(0, 0), 
     new Point(alphaMask.getWidth(), 0), 
     new float[]{0, 1}, 
     new Color[]{new Color(0, 0, 0, 255), new Color(0, 0, 0 , 0)}); 
g2d.setPaint(lgp); 
g2d.fillRect(0, 0, alphaMask.getWidth(), alphaMask.getHeight()); 
g2d.dispose(); 

這裏的關鍵是,我們並不真正關心實物顏色,只有它的alpha屬性,因爲這將決定兩個圖像是如何掩蓋起來......

然後,我們應用面具...

BufferedImage faded = applyMask(original, alphaMask, AlphaComposite.DST_IN); 

裏面居然調用此實用工具方法...

public static BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) { 

    BufferedImage maskedImage = null; 
    if (sourceImage != null) { 

     int width = maskImage.getWidth(); 
     int height = maskImage.getHeight(); 

     maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 
     Graphics2D mg = maskedImage.createGraphics(); 

     int x = (width - sourceImage.getWidth())/2; 
     int y = (height - sourceImage.getHeight())/2; 

     mg.drawImage(sourceImage, x, y, null); 
     mg.setComposite(AlphaComposite.getInstance(method)); 

     mg.drawImage(maskImage, 0, 0, null); 

     mg.dispose(); 
    } 

    return maskedImage; 

} 

這BAS ically使用AlphaComposite了「目的地」的面膜敷到的原始圖像,這將導致...

(原左邊,右邊阿爾法)

Alpha

而只是爲了證明這一點,我改變了框架的內容窗格的背景色爲RED

enter image description here

+0

謝謝,那正是我一直在尋找的! – WiErD0