i用这种方法在帧中绘制图形。
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();
}
我想选择透明度为50%或其他整数。
private Image selectedImage = new ImageIcon(Main.class.getResource("../pic/something.jpg")).getImage();
这是选择的图像,并且效果很好。
调整一些图像 -> 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