项目源码
新增资源文件
新增Image图像处理类
新增sprite包,里面新增Image.java类
package sprite; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; public class Image { private BufferedImage _img; private int _width; private int _height; public Image(String path){ try { _img = ImageIO.read(getClass().getClassLoader().getResourceAsStream(path)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } _width = _img.getWidth(null); _height = _img.getHeight(null); _img = makeTransparent(_img); } private BufferedImage makeTransparent(BufferedImage tmpImage) { int h=tmpImage.getHeight(null); int w=tmpImage.getWidth(null); BufferedImage resultImage=new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); // assume the upperleft corner of the original image is a transparent pixel Color trans = new Color(255,0,255); Color transOther = new Color(252,0,255); int transparentColor=trans.getRGB(); int transparentColorOther=transOther.getRGB(); for (int y=0;y<h;y++) for (int x=0;x<w;x++) { int color=tmpImage.getRGB(x,y); if (color==transparentColor) color=color & 0x00FFFFFF; // clear the alpha flag else if(color==transparentColorOther) color=color & 0x00FFFFFF; resultImage.setRGB(x,y,color); } return resultImage; } public BufferedImage getImage(){ return _img; } }
图片的透明处理
makeTransparent方法:
1640594977(1).png
遍历图像的每一个像素,通过以下代码清除图片中颜色为上图的2种粉色(我们的资源有2种粉色)
color=color & 0x00FFFFFF;
这样处理之后,原图
01.png
就变成了透明的。
GameApp的改变
1640595269(1).png
本节最终效果