我正在尝试制作一个马里奥游戏克隆,现在,在我的构造函数中,我有一个方法应该使某种颜色透明而不是当前的粉红色(R:255,G:0,B :254)。根据 Photoshop,十六进制值为 ff00fe。我的方法是:
public Mario(){
this.state = MarioState.SMALL;
this.x = 54;
this.y = 806;
URL spriteAtLoc = getClass().getResource("sprites/Mario/SmallStandFaceRight.bmp");
try{
sprite = ImageIO.read(spriteAtLoc);
int width = sprite.getWidth();
int height = sprite.getHeight();
int[] pixels = new int[width * height];
sprite.getRGB(0, 0, width, height, pixels, 0, width);
for (int i = 0; i < pixels.length; i++) {
if (pixels[i] == 0xFFff00fe) {
pixels[i] = 0x00ff00fe; //this is supposed to set alpha value to 0 and make the target color transparent
}
}
} catch(IOException e){
System.out.println("sprite not found");
e.printStackTrace();
}
}
它运行并编译,但是当我渲染它时, Sprite 的结果完全相同。 (编辑:也许值得注意的是,我的paintComponent(g)方法中没有super.paintComponent(g)。 Sprite 是.bmps。
最佳答案
您仅使用 BufferedImage.getRGB 检索像素。这将返回 BufferedImage 特定区域中数据的副本。
您对返回的 int[]
所做的任何更改都不会自动反射(reflect)回图像中。
要更新图像,您需要在更改 int[]
后调用 BufferedImage.setRGB
:
sprite.setRGB(0, 0, width, height, pixels, 0, width);
<小时/>
您可能应该进行的另一个更改(这涉及一些猜测,因为我没有您的 bmp 来测试) - ImageIO.read
返回的 BufferedImage 可能具有 BufferedImage 类型.TYPE_INT_RGB
- 意味着它没有 Alpha channel 。您可以通过打印 sprite.getType()
来验证,如果打印 1
,则它是没有 Alpha channel 的 TYPE_INT_RGB。
要获取 Alpha channel ,请创建一个大小合适的新 BufferedImage,然后在该图像上设置转换后的 int[]
,然后使用新图像:
BufferedImage newSprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
newSprite.setRGB(0, 0, width, height, pixels, 0, width);
sprite = newSprite; // Swap the old sprite for the new one with an alpha channel
关于java - 为什么我的去除这种颜色的方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45450976/