2012-07-18 94 views
8

在項目中,我想同時調整大小並更改圖像的不透明度。到目前爲止,我認爲我已經調整了大小。我使用如此定義的方法來完成調整大小:更改圖片不透明度

public BufferedImage resizeImage(BufferedImage originalImage, int type){ 

    initialWidth += 10; 
    initialHeight += 10; 
    BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type); 
    Graphics2D g = resizedImage.createGraphics(); 
    g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null); 
    g.dispose(); 

    return resizedImage; 
} 

我從這裏得到了這段代碼。我找不到解決方案是改變不透明度。這就是我想知道如何去做(如果可能的話)。提前致謝。

UPDATE

我嘗試這樣做的代碼,以顯示與透明內側和外側的圓的圖像(見下圖)生長和越來越低不透明的,但它沒有工作。我不確定有什麼問題。所有的代碼是在一個名爲動畫

public Animation() throws IOException{ 

    image = ImageIO.read(new File("circleAnimation.png")); 
    initialWidth = 50; 
    initialHeight = 50; 
    opacity = 1; 
} 

public BufferedImage animateCircle(BufferedImage originalImage, int type){ 

     //The opacity exponentially decreases 
     opacity *= 0.8; 
     initialWidth += 10; 
     initialHeight += 10; 

     BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type); 
     Graphics2D g = resizedImage.createGraphics(); 
     g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); 
     g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null); 
     g.dispose(); 

     return resizedImage; 

} 

我這樣調用類:

Animation animate = new Animation(); 
int type = animate.image.getType() == 0? BufferedImage.TYPE_INT_ARGB : animate.image.getType(); 
BufferedImage newImage; 
while(animate.opacity > 0){ 

    newImage = animate.animateCircle(animate.image, type); 
    g.drawImage(newImage, 400, 350, this); 

} 
+0

爲了更快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2012-07-19 02:29:25

回答

19

首先確保你傳遞給方法的種類中,包括alpha通道,像

BufferedImage.TYPE_INT_ARGB 

然後就在繪製新圖像之前,請調用Graphics2D方法setComposite,如下所示:

float opacity = 0.5f; 
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); 

將設置不透明度爲50%。

+0

我會盡力回覆你,如果它有效。 – pasawaya 2012-07-19 00:16:25

+0

此外,只是檢查,1對應完全可見,0對透明?謝謝。還有,我在繪製之前還是之後調用'setComposite()'? – pasawaya 2012-07-19 00:18:02

+1

0是透明的,1是不透明的 – MadProgrammer 2012-07-19 00:46:17