像素与Config.ALPHA_8完美碰撞

我发现这个像素完美碰撞检查代码并在我的代码中使用它:

public boolean isCollisionDetected(Bitmap bitmap1, int x1, int y1, Bitmap bitmap2, int x2, int y2) { Rect bounds1 = new Rect(x1, y1, x1 + bitmap1.getWidth(), y1 + bitmap1.getHeight()); Rect bounds2 = new Rect(x2, y2, x2 + bitmap2.getWidth(), y2 + bitmap2.getHeight()); if (Rect.intersects(bounds1, bounds2)) { Rect collisionBounds = getCollisionBounds(bounds1, bounds2); for (int i = collisionBounds.left; i < collisionBounds.right; i++) { for (int j = collisionBounds.top; j < collisionBounds.bottom; j++) { int bitmap1Pixel = bitmap1.getPixel(i - x1, j - y1); int bitmap2Pixel = bitmap2.getPixel(i - x2, j - y2); if (isFilled(bitmap1Pixel) && isFilled(bitmap2Pixel)) { return true; } } } } return false; } private Rect getCollisionBounds(Rect rect1, Rect rect2) { int left = (int) Math.max(rect1.left, rect2.left); int top = (int) Math.max(rect1.top, rect2.top); int right = (int) Math.min(rect1.right, rect2.right); int bottom = (int) Math.min(rect1.bottom, rect2.bottom); return new Rect(left, top, right, bottom); } private boolean isFilled(int pixel) { return pixel != Color.TRANSPARENT; } 

它工作得很好,没有任何问题。 直到我使用此代码将图像设置为Config_Alpha_8(因为ram问题):

  private Bitmap convert(Bitmap bitmap, Bitmap.Config config) { Bitmap convertedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), config); Canvas canvas = new Canvas(convertedBitmap); Paint paint = new Paint(); paint.setColor(Color.BLACK); canvas.drawBitmap(bitmap, 0, 0, paint); return convertedBitmap; } 

为什么什么都不会发生,它确实进入了isCollisioDetected,我已经检查了日志! 但它不会检测碰撞..任何人都可以提供工作function来检查位图与config_alpha_8的像素完美碰撞?

在具有ALPHA_8配置的位图上调用getPixel()将始终返回零。 这似乎是一个错误

您可以通过将每个位图的像素存储为字节数组来解决此问题:

 byte[] pixelData = getPixels(convert(bitmap, Bitmap.Config.ALPHA_8)); ... public byte[] getPixels(Bitmap bmp) { int bytes = bmp.getRowBytes() * bmp.getHeight(); ByteBuffer buffer = ByteBuffer.allocate(bytes); bmp.copyPixelsToBuffer(buffer); return buffer.array(); } 

您需要稍微修改碰撞检测function:

 public boolean isCollisionDetected(byte[] pixels1, Bitmap bitmap1, int x1, int y1, byte[] pixels2, Bitmap bitmap2, int x2, int y2) { int width1 =bitmap1.getWidth(); int height1=bitmap1.getHeight(); int width2 =bitmap2.getWidth(); int height2=bitmap2.getHeight(); Rect bounds1 = new Rect(x1, y1, x1 + width1, y1 + height1); Rect bounds2 = new Rect(x2, y2, x2 + width2, y2 + height2); if (Rect.intersects(bounds1, bounds2)) { Rect collisionBounds = getCollisionBounds(bounds1, bounds2); for (int i = collisionBounds.left; i < collisionBounds.right; i++) { for (int j = collisionBounds.top; j < collisionBounds.bottom; j++) { byte bitmap1Pixel = pixels1[((j - y1) * width1) + (i - x1)]; byte bitmap2Pixel = pixels2[((j - y2) * width2) + (i - x2)]; if (isFilled(bitmap1Pixel) && isFilled(bitmap2Pixel)) { return true; } } } } return false; } 

(...您可能希望将位图参数更改为这些位图的相应宽度和高度,并调用recycle()。)

Android Config_Alpha_8不保存颜色信息,因此在绘制位图时,添加绘图将不执行任何操作,并且所有isFilled检查将返回false。

虽然整齐的代码。