1

我有两个 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 错误访问权限。它并不总是发生,但只有当要比较的像素数量很大时才会发生。

4

1 回答 1

1

一种更简单的方法是查看基础数据并进行比较。

将每个 UIView 写入图像。(来自这个答案

#import <QuartzCore/QuartzCore.h>

@implementation UIView (Ext)
- (UIImage*) renderToImage
{
  // IMPORTANT: using weak link on UIKit
  if(UIGraphicsBeginImageContextWithOptions != NULL)
  {
    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
  } else {
    UIGraphicsBeginImageContext(self.frame.size);
  }

  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();  
  return image;
}

比较位图。您可以逐字逐句,也可以对每个单词进行哈希处理

#import <CommonCrypto/CommonDigest.h>:

unsigned char result[16];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(inImage)];
CC_MD5([imageData bytes], [imageData length], result);
NSString *imageHash = [NSString stringWithFormat:
                       @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                       result[0], result[1], result[2], result[3], 
                       result[4], result[5], result[6], result[7],
                       result[8], result[9], result[10], result[11],
                       result[12], result[13], result[14], result[15]
                       ];

或以无数比您拥有的更快的方式进行比较。

于 2013-09-04T03:49:34.557 回答