Pixel collision detection / overlap between two images

I have two UIImageViews that contain images with some transparent area. Is there a way to check if an opaque area is colliding between both images?

Thanks.

[UPDATE] So this is what I still have, unfortunately, it still does not work, but I can’t understand why.

if (!CGRectIntersectsRect(frame1, frame2)) return NO; NSLog(@"OverlapsPixelsInImage:withImage:> Images Intersect"); UIImage *img1 = imgView1.image; UIImage *img2 = imgView2.image; CGImageRef imgRef1 = [img1 CGImage]; CGImageRef imgRef2 = [img2 CGImage]; float minx = MIN(frame1.origin.x, frame2.origin.x); float miny = MIN(frame1.origin.y, frame2.origin.y); float maxx = MAX(frame1.origin.x + frame1.size.width, frame2.origin.x + frame2.size.width); float maxy = MAX(frame1.origin.y + frame1.size.height, frame2.origin.y + frame2.size.height); CGRect canvasRect = CGRectMake(0, 0, maxx - minx, maxy - miny); size_t width = floorf(canvasRect.size.width); size_t height = floorf(canvasRect.size.height); NSUInteger bitsPerComponent = 8; NSUInteger bytesPerRow = 4 * width; unsigned char *rawData = calloc(width * height, sizeof(*rawData)); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); CGColorSpaceRelease(colorSpace); CGContextTranslateCTM(context, 0, canvasRect.size.height); CGContextScaleCTM(context, 1.0, -1.0); CGContextClipToMask(context, CGRectMake(frame2.origin.x - minx, frame2.origin.y - miny, frame2.size.width, frame2.size.height), imgRef2); CGContextDrawImage(context, CGRectMake(frame1.origin.x - minx, frame1.origin.y - miny, frame1.size.width, frame1.size.height), imgRef1); CGContextRelease(context); int byteIndex = 0; for (int i = 0; i < width * height; i++) { CGFloat alpha = rawData[byteIndex + 3]; if (alpha > 128) { NSLog(@"collided in byte: %d", i); free(rawData); return YES; } byteIndex += 4; } free(rawData); return NO; 
+4
source share
2 answers

You can draw both alpha channels of both images in one bitmap context, and then view the data for any transparent pixels. Take a look at the clipRectToPath() code in Clipping CGRect on CGPath . This is a solution to another problem, but the approach is the same. Instead of using CGContextFillPath() to draw in context, just draw both images.

Here's the thread:

  • Create an alpha-only bitmap context ( kCGImageAlphaOnly )
  • Draw everything you want to compare with it.
  • Swipe the pixels looking at the value. In my example, he considers that < 128 is "transparent". If you want completely transparent, use == 0 .
  • When you find a transparent pixel, the example simply notes which column it was in. In your problem, you can simply return YES , or you can use this data to form another mask.
+1
source

Not easy, you basically need to read data in bitmap bitmaps and navigate in pixels.

+1
source

All Articles