【问题标题】:Java Graphics2D draw image with transparent colorJava Graphics2D 用透明颜色绘制图像
【发布时间】:2014-05-08 07:05:10
【问题描述】:

我想知道对简单问题的尽可能简单的解决方案(到目前为止我发现只有非常复杂的解决方案):如何在 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);        
}

我的图片周围是白色的,我不想画。

【问题讨论】:

    标签: java awt draw graphics2d


    【解决方案1】:

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

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

    【讨论】:

    • 所以你发布一个问题,然后在一个小时内自己回答。好努力。
    猜你喜欢
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2013-04-25
    • 2015-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    相关资源
    最近更新 更多