Java Graphics2D使用透明颜色绘制图像

时间:2014-03-28 17:16:49

标签: java awt draw graphics2d

我想知道尽可能简单的解决方案(到目前为止,我发现只有非常复杂的解决方案)到简单的问题:如何在Graphics2D中绘制图像并将一种颜色设置为完全透明?

到目前为止,我正在尝试这样的事情,但没有成功:

private Image head;
public void draw(Graphics2D g) {      
    g.setComposite(AlphaComposite.Src);
    Color transparentWhite = new Color(255,255,255,1);
    g.drawImage(head, (int)posX, (int)posY, transparentWhite, null);        
}

我周围有白色的照片,我不想画。

1 个答案:

答案 0 :(得分:2)

好的,终于找到了答案,这是我找到的最简单的解决方案。

private Image head;

//This is constructor, here I use method that adding transparency to image.
public Character(BufferedImage head){
        this.head = makeColorTransparent(head, Color.WHITE);
}

public void draw(Graphics2D g) {
        g.drawImage(head, (int) posX, (int) posY, null); //variable head is saved with transparency, so now it is drawing right
}

//Just copy-paste this method
public static Image makeColorTransparent(BufferedImage im, final Color color) {
    ImageFilter filter = new RGBImageFilter() {

        // the color we are looking for... Alpha bits are set to opaque
        public int markerRGB = color.getRGB() | 0xFF000000;

        public final int filterRGB(int x, int y, int rgb) {
            if ((rgb | 0xFF000000) == markerRGB) {
                // Mark the alpha bits as zero - transparent
                return 0x00FFFFFF & rgb;
            } else {
                // nothing to do
                return rgb;
            }
        }
    };

    ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
}