Drawing a transparent BufferedImage over a non-transparent BufferedImage

时光怂恿深爱的人放手 提交于 2019-12-08 04:11:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10144599/drawing-a-transparent-bufferedimage-over-a-non-transparent-bufferedimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!