[英]Create Region from non-transparent pixels of a PNG image
I need to extract from a PNG image a pixel perfect Region to detect collisions. 我需要从PNG图像中提取一个像素完美区域来检测碰撞。 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: 以下是Image类的实现:
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. 碰撞检测不起作用,当我从返回的区域调用方法
.isEmpty()
,它返回true。 Any idea why? 知道为什么吗?
You can just create a function inside of the AndroidImage class, 您可以在AndroidImage类中创建一个函数,
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.
我认为您的问题可能一直是您在调用getRGB,这似乎并没有给您Alpha值。
I don't know how to deal with the actual detection part with two regions, though... 我不知道如何处理两个区域的实际检测部分...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.