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;
source share