gpt4 book ai didi

java - 使用 java swing.image 更改透明度的方法

转载 作者:行者123 更新时间:2023-12-02 11:56:47 25 4
gpt4 key购买 nike

我用这种方法在框架中绘制图形。

public void paint(Graphics g) {  
screenImage = createImage(1280, 720);
screenGraphic = screenImage.getGraphics();
screenDraw((Graphics2D) screenGraphic);
//g.drawImage(BG, 0, 0, null);
g.drawImage(screenImage, 0, 0, null);
}

public void screenDraw(Graphics2D g) {
g.drawImage(BG, 0, 0, null);
Graphics2D g2 = (Graphics2D)g;
if(isMainScreen) {
//g2.setComposite(alphaComposite);
g2.drawImage(selectedImage, 100, 220, null);
}
paintComponents(g);
this.repaint();
}

我希望 selectedImage 的透明度为 50% 或其他整数。

private Image selectedImage = new ImageIcon(Main.class.getResource("../pic/something.jpg")).getImage(); 

这是选定的图像,效果很好。

最佳答案

稍微调整一下Image -> BufferedImage代码,然后可以将每个像素设置为透明

Image selectedImage = new ImageIcon([...]).getImage();

//Image -> BufferedImage code
BufferedImage img = new BufferedImage(selectedImage.getWidth(null), selectedImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
g.drawImage(selectedImage, 0, 0, null);
g.dispose();

//set each pixel to be transparent
int transparency = 127; //0-255, 0 is invisible, 255 is opaque
int colorMask = 0x00FFFFFF; //AARRGGBB
int alphaShift = 24;
for(int y = 0; y < img.getHeight(); y++)
for(int x = 0; x < img.getWidth(); x++)
img.setRGB(x, y, (img.getRGB(x, y) & colorMask) | (transparency << alphaShift));

//img is now transparent, can replace selectedImage if you want (optional)
selectedImage = img;

如果您使用ImageIO.read(File)而不是 ImageIcon.getImage(),它会直接给你一个 BufferedImage

关于java - 使用 java swing.image 更改透明度的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47555046/

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