2015-05-25 64 views
0

如何將通過這裏的圖標着色爲不同的顏色?假設我想拍攝一張白色圖像並使其變得更暗。我看了看BufferedImages等,但我似乎無法找到任何適合我使用的設置的東西。我還應該注意到,如果這有所作爲,我正在將圖像繪製到JLabel上。如何給一個ImageIcon着色

這裏是我使用的來源,以便您可以瞭解我正在處理的內容。

public class Icon extends ImageIcon{ 

    private int scale = 1; 
    private boolean mirror = false; 

    public Icon(URL url) throws IOException{ 
     super(ImageIO.read(url)); 
    } 

    public void setScale(int scale){ 
     this.scale = scale; 
    } 

    @Override 
    public synchronized void paintIcon(Component c, Graphics g, int x, int y) { 
     Graphics2D g2 = (Graphics2D)g.create(); 
     int height = 0, width = this.getIconWidth(), x1 = 1; 
     if(mirror || scale != 1){ 
      height = -this.getIconHeight(); 
     } 
     if(mirror){ 
      x1 = -1; 
     }else{ 
      width = 0; 
     } 
     g2.translate(width * scale, height); 
     g2.scale(x1 * scale, 1 * scale); 
     super.paintIcon(c, g2, x, y); 
    } 

    public boolean isMirror() { 
     return mirror; 
    }  

    public void setMirror(boolean mirror) { 
     this.mirror = mirror; 
    } 
} 
+0

從重複以上鍊接,直接使用'ColorTintFilter'或者修改您的需求。它會讓你的圖像變得柔和。但是,如果您只是想讓圖像稍暗一些,則可以用透明黑色(即「新顏色(0x20000000,true)」或類似顏色)將其覆蓋。 – haraldK

回答

1

你需要創建一個新的BufferedImage,使轉變爲:

public BufferedImage colorImage(BufferedImage loadImg, int red, int green, int blue) { 
    BufferedImage img = new BufferedImage(loadImg.getWidth(), loadImg.getHeight(), 
     BufferedImage.TRANSLUCENT); 
    Graphics2D graphics = img.createGraphics(); 
    Color newColor = new Color(red, green, blue, 0 /* alpha needs to be zero */); 
    graphics.setXORMode(newColor); 
    graphics.drawImage(loadImg, null, 0, 0); 
    graphics.dispose(); 
    return img; 
} 
+0

我試過之前,它似乎不工作,即使我將圖像設置爲100%黑色,它仍然使顏色都怪異。 – Cyphereion