[英]Why isn't my method for removing this color working?
我正在嘗試制作Mario游戲克隆,現在,在我的構造函數中,我有一種方法應該使某種顏色透明而不是當前的粉紅色(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();
}
}
它可以運行和編譯,但是在渲染時,精靈會完全一樣。 (編輯:也許值得注意的是,我的paintComponent(g)方法中沒有super.paintComponent(g)。這些圖片是.bmps。
您僅使用BufferedImage.getRGB
檢索像素。 這將返回BufferedImage特定區域中的數據副本 。
您對返回的int[]
所做的任何更改都不會自動反映回圖像中。
要更新圖像,您需要在更改int[]
之后調用BufferedImage.setRGB
:
sprite.setRGB(0, 0, width, height, pixels, 0, width);
另一個變化你應該做(這涉及到一個小猜測,因為我沒有你的BMP來測試) -返回的BufferedImage的ImageIO.read
可能有型BufferedImage.TYPE_INT_RGB
-這意味着它不具有alpha通道。 您可以通過打印sprite.getType()
進行驗證,如果打印出1
,則為不帶alpha通道的TYPE_INT_RGB。
要獲得Alpha通道,請創建一個大小合適的新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
BMP圖像不提供Alpha通道,您必須手動設置它(就像在代碼中一樣)...
當您檢查像素是否具有某種顏色時,您必須不使用alpha進行檢查(BMP沒有alpha始終為0x0)。
if (pixels[i] == 0x00ff00fe) { //THIS is the color WITHOUT alpha
pixels[i] = 0xFFff00fe; //set alpha to 0xFF to make this pixel transparent
}
簡而言之:您沒事,但把它混了一點^^
這有效:
private BufferedImage switchColors(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// top left pixel is presumed to be BG color
int rgb = img.getRGB(0, 0);
for (int xx=0; xx<w; xx++) {
for (int yy=0; yy<h; yy++) {
int rgb2 = img.getRGB(xx, yy);
if (rgb2!=rgb) {
bi.setRGB(xx, yy, rgb2);
}
}
}
return bi;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.