I have two UIViews and would like to do a pixel by pixel comparison. Based on this answer here How to get the color of a pixel in an UIView? I have the following method.
- (UIColor *)colorOfPoint:(CGPoint)point view:(UIView *)view {
unsigned char pixel[4] = {0};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM(context, -point.x, -point.y);
[view.layer renderInContext:context];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
//NSLog(@"pixel: %d %d %d %d", pixel[0], pixel[1], pixel[2], pixel[3]);
UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
return color;
}
And then to do the pixel comparisons I loop through
- (void)comparePixels {
for (int height = 0; height <= view1.frame.size.height; height++) {
for (int width = 0; width <= view1.frame.size.width; width++) {
UIColor *view1Color = [self colorOfPoint:CGPointMake(height, width) view:view1];
UIColor *view2Color = [self colorOfPoint:CGPointMake(height, width) view:view2];
if (![view1Color isEqual:view2Color]) {
NSLog(@"%d %d", height, width);
}
}
}
}
So I have two questions: 1) This approach is incredibly slow. Is there a faster way? 2) After several iterations, I sometimes get an exec bad access on the line [view.layer renderInContext:context]. It doesn't always happen but only when the number of pixels to compare is large.