问题描述
在绘制BufferedImages时遇到问题。我正在使用基于2D瓷砖的地图编辑器,当我绘制瓷砖时,它首先绘制了下一层,然后是顶层。
像这样:
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);
}
请注意,此方法在扩展JLabel的类中。它实际上是在重绘已设置的ImageIcon。现在,要了解该问题,您必须意识到在创建objectLayer BufferedImage之前,将检查每个像素是否具有某种颜色。如果像素是该颜色,则将像素设置为全白,alpha值为0(这样它将是透明的)。示例:
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.
问题是,这对某些图像有效,而对某些图像无效。在某些图像上,当我去绘制顶层时,无论如何它只会绘制白色(就像alpha值未设置为0一样),而在其他图像上,它像超级按钮一样工作并且不会绘制白色像素
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.
我一直只使用.png图像,所以我知道它与格式无关。我尝试了很多不同的方法,如果有人可以帮忙,我就会陷入困境。
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.
推荐答案
我相信默认情况下BufferedImage不支持Alpha通道。构造BufferedImage时,传入BufferedImage.TYPE_INT_ARGB可解决此问题。
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.
这篇关于在非透明的BufferedImage上绘制一个透明的BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!