gpt4 book ai didi

iOS:两个 UIView 的逐像素比较

转载 作者:行者123 更新时间:2023-11-29 13:06:06 25 4
gpt4 key购买 nike

我有两个 UIView,想逐个像素地进行比较。基于这里的答案 How to get the color 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 bad access。它并不总是发生,只有当要比较的像素数很大时才会发生。

最佳答案

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

将每个 UIView 写成一张图片。 (来自this answer)

#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]
];

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

关于iOS:两个 UIView 的逐像素比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18605004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com