简体   繁体   中英

Way to change transparency with java swing.image

I draw graphics in frame with this methods.

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

I want to have selectedImage to be transparency 50% or other integer.

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

this is selectedImage, and it works well.

Adapt a bit of Image -> BufferedImage code, and then you can set each pixel to be transparent

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;

If you use ImageIO.read(File) instead of ImageIcon.getImage() , it will give you a BufferedImage directly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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