I need to extract from a PNG image a pixel perfect Region to detect collisions. I found the following code to be a solution:
public static Region create(Image image) {
Region region = new Region();
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
if (Color.alpha(image.getRGB(i, j)) == 255) {
region.op(new Rect(i, j, 1, 1), Region.Op.UNION);
}
}
}
return region;
}
The following is the implementation of the Image class:
public class AndroidImage implements Image {
Bitmap bitmap;
ImageFormat format;
public AndroidImage(Bitmap bitmap, ImageFormat format) {
this.bitmap = bitmap;
this.format = format;
}
@Override
public int getWidth() {
return bitmap.getWidth();
}
@Override
public int getHeight() {
return bitmap.getHeight();
}
@Override
public int getRGB(int x, int y) {
return bitmap.getPixel(x, y);
}
@Override
public ImageFormat getFormat() {
return format;
}
@Override
public void dispose() {
bitmap.recycle();
}
}
Collision detection doesn't work and when i call the method .isEmpty()
from the returned region, it returns true. Any idea why?
You can just create a function inside of the AndroidImage class,
public Region getTranspRegion()
{
BitmapDrawable bitmapChecker = new BitmapDrawable(bitmap);
Region transpRegion = bitmapChecker.getTransparentRegion();
return transpRegion;
}
and then in your main class:
Region imageRegion = new Region(imageX, imageY, image.getWidth(), image.getHeight());
Region collisionRegion = new Region(imageRegion);
collisionRegion.op(image.getTranspRegion(), Op.DIFFERENCE);
A lot easier than checking every pixel. I think your problem MIGHT have been the fact that you were calling getRGB, which seems like it would give you no Alpha value.
I don't know how to deal with the actual detection part with two regions, though...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.