2013-06-04 45 views
1

我遇到了保持圖像透明的問題。如何在閱讀圖像時保持透明度不變? (Java)

比方說,我們有一個名爲imageA.png的圖像,我們想要導入它。爲了保持accessable其他方法,我們將首先這樣聲明:

private BufferedImage imageA; 

然後再導入:

className(){ 
    try{ 
     imageA = ImageIO.read(className.class.getResourceAsStream("floor.png")); 
    }catch(IOException ex){ 
     ex.printStackTrace(); 
    } 
} 

然後我們就可以在paintComponent方法使用它,如下所示:

public void paintComponent(Graphics g){ 
    g.drawImage(imageA, 0, 0, null); 
    //using Graphics.drawImage(Image img, int dstx1, int dsty1, int dstx2, int dsty2,int srcx1, int srcy1, int srcx2, int srcy2, ImageObserver observer) in the real program, don't know if that matters? 
} 

現在讓我們說,在我的原始圖片中,imageA.png有一個透明區域,由於某種原因它現在丟失了。至少,在我的輸出中。在我使用這種繪製圖像的方式中,我將它繪製在另一幅圖像的頂部,但在原始圖像中它看起來是透明的。爲什麼是這個,我該如何解決它?

+0

不要在'paintComponent'裏面調用'repaint'並且首先調用'super.paintComponent()'來繪製背景顏色。在構造函數中或者'setBackground(Color.CYAN);'檢查透明度。 –

+0

也許發佈截圖,並鏈接到floor.png? ImageIO將保持透明的PNG透明區域,我的猜測是你的組件背景讓你感到困惑。嘗試setOpaque(false)。另外,如果你想知道是否有什麼問題,試試吧! :-) – haraldK

回答

1

代碼貼在這裏

  • 添加super.paintComponent(g),清除以前的畫,否則畫累積

  • 不叫repaint();paintComponent,因爲能引起無限循環,從內repaint();,這種方法是用編程方式來重繪,例如最好的辦法,如果從Swing Timer

你的問題

  • 爲更好地幫助越早張貼SSCCE,短,可運行,編譯,有BuferredImage從代碼生成或從看房網站
鏈接
1

我的猜測是,您需要在組件中使用setOpaque(false)(覆蓋paintComponent(Graphics g))。

ImageIO保持圖像的透明部分透明。

相關問題