Pixel perfect collision with Config.ALPHA_8

后端 未结 2 1558
失恋的感觉
失恋的感觉 2021-01-05 18:28

I\'ve found this code of pixel perfect collision checking and used it in my code:

public  boolean isCollisionDetected(Bitmap bitmap1, int x1, int y1,
               


        
相关标签:
2条回答
  • 2021-01-05 18:44

    Calling getPixel() on a bitmap with ALPHA_8 configuration will always return zero. This seems to be a bug

    You can work around this problem by storing the pixels of each bitmap as a byte array:

    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();
    }
    

    You will need to modify your collision detection function a little:

    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;
        }
    

    (... you might want to change the bitmap parameters into the respective width and height of the those bitmaps and call recycle().)

    0 讨论(0)
  • 2021-01-05 18:52

    Android Config_Alpha_8 does not save color information, so when you draw the bitmap, adding the paint will do nothing, and all isFilled checks will return false.

    Neat piece of code though.

    0 讨论(0)
提交回复
热议问题