简体   繁体   English

Java Graphics2D用透明颜色绘制图像

[英]Java Graphics2D draw image with transparent color

I want to know as simple as possible solution (so far I found only very complex solution) to simple question : How to draw an image in Graphics2D and set one color as fully transparent? 我想知道一个简单问题的尽可能简单的解决方案(到目前为止,我只找到了非常复杂的解决方案):如何在Graphics2D中绘制图像并将一种颜色设置为完全透明?

So far, I was trying something like this, but with no success : 到目前为止,我正在尝试类似的尝试,但没有成功:

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

I have picture with white color around it which I do not want to draw. 我周围有白色的图片,不想绘制。

Ok, finally found an answer, this is the most easies solution I have found. 好了,终于找到了答案,这是我找到的最简单的解决方案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM