我有两个 UIView,想逐像素进行比较。基于这里的答案 How to get a pixel of a pixel in an UIView? 我有以下方法。
- (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;
}
然后循环进行像素比较
- (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);
}
}
}
}
所以我有两个问题:1)这种方法非常慢。有更快的方法吗?2) 经过几次迭代后,我有时会在 [view.layer renderInContext:context] 行上获得 exec 错误访问权限。它并不总是发生,但只有当要比较的像素数量很大时才会发生。