【问题标题】:How to tint an ImageIcon [duplicate]如何为 ImageIcon 着色 [重复]
【发布时间】:2015-05-25 18:37:23
【问题描述】:

如何将通过此处的图标着色为不同的颜色?假设我想拍一张白色的照片并让它变暗一点。我已经研究过 BufferedImages 等,但我似乎找不到任何适合我正在使用的设置的东西。我还应该注意,如果这会有所不同,我会将图像绘制到 JLabel 上。

这是我正在使用的来源,以便您了解我正在使用的内容。

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;
    }
}

【问题讨论】:

  • 使用上面重复链接中的ColorTintFilter,可以直接使用,也可以根据需要进行修改。它会很好地为您的图像着色。然而,如果你只是想让你的图像稍微暗一点,你可以用透明的黑色覆盖它(即new Color(0x20000000, true)或类似的)。

标签: java graphics bufferedimage imageicon tint


【解决方案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;
}

【讨论】:

  • 我之前试过了,好像不行,即使我把图片设置为100%黑色,颜色还是很奇怪。
猜你喜欢
  • 2016-05-13
  • 1970-01-01
  • 2020-11-26
  • 2016-03-03
  • 1970-01-01
  • 2013-09-08
  • 2021-12-03
  • 2012-12-30
  • 2010-11-29
相关资源
最近更新 更多