gpt4 book ai didi

Java Graphics2D绘制具有透明颜色的图像

转载 作者:行者123 更新时间:2023-11-30 08:24:45 27 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于Java Graphics2D绘制具有透明颜色的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22719275/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com