简体   繁体   中英

Drawing a transparent BufferedImage over a non-transparent BufferedImage

I'm having a problem when it comes to drawing BufferedImages. I'm working on a 2D tile-based map editor and when I draw a tile, it first draws the lower layer followed by the top layer. like so:

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawImage(tileLayer, 0, 0, null);
    g.drawImage(objectLayer, 0, 0, null);
}

Note that this method is in a class which extends JLabel. It's actually redrawing the ImageIcon which was set. Now, to understand the problem you must realize that before the objectLayer BufferedImage is created, each pixel is checked for a certain color. If the pixel is that color, then the pixel is set to all white with an alpha value of 0 (so that it will be transparent). Example:

    int transparentRed = transparentColor.getRed();
    int transparentGreen = transparentColor.getGreen();
    int transparentBlue = transparentColor.getBlue();


for (int x = 0; x < image.getWidth(); x++)
{
    for (int y = 0; y < image.getHeight(); y++)
    {
        int color = i.getRGB(x, y);

        int red = (color & 0x00FF0000) >> 16;
        int green = (color & 0x0000FF00) >> 8;
        int blue = color & 0x000000FF;

        // If the pixel matches the specified transparent color
        // Then set it to an absolute white with alpha at 0
        if (red == transparentRed && green == transparentGreen && blue == transparentBlue)
            i.setRGB(x, y, 0x00FFFFFF);
    }
}

    return i; 

The point is to draw the top layer over the lower layer without affecting any of the previously placed lower layer pixels. The white pixels of the top layer should just not appear.

The problem is that this works on some images and on others it doesn't. On certain images, when I go to draw the top layer, it just draws the white in anyways (as if the alpha value isn't set to 0) and on other images it works like a charm and the white pixels aren't drawn in.

I have been using only .png images so I know that it doesn't have to do with the formatting. I've tried quite a few different things and I'm stuck if anyone can help out.

I believe that by default the BufferedImage doesn't support an alpha channel. When constructing the BufferedImage, passing in BufferedImage.TYPE_INT_ARGB fixed the problem.

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