88
99#import " UIImage+G8Equal.h"
1010
11+ static CGFloat const kG8MinimalSimilarity = 0.99 ;
12+
1113@implementation UIImage (G8Equal)
1214
1315- (BOOL )g8_isEqualToImage : (UIImage *)image
@@ -16,16 +18,62 @@ - (BOOL)g8_isEqualToImage:(UIImage *)image
1618 return YES ;
1719 }
1820
21+ CGFloat similarity = [[self g8_normalizedImage ] g8_similarityWithImage: [image g8_normalizedImage ]];
22+ return similarity > kG8MinimalSimilarity ;
23+ }
24+
25+ - (uint32_t *)pixels
26+ {
27+ CGSize size = [self size ];
28+ int width = size.width ;
29+ int height = size.height ;
30+
31+ uint32_t *pixels = (uint32_t *) malloc (width * height * sizeof (uint32_t ));
32+ memset (pixels, 0 , width * height * sizeof (uint32_t ));
33+
34+ CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB ();
35+
36+ CGContextRef context = CGBitmapContextCreate (pixels, width, height, 8 , width * sizeof (uint32_t ), colorSpace,
37+ kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast );
38+ CGContextDrawImage (context, CGRectMake (0 , 0 , width, height), self.CGImage );
39+
40+ CGContextRelease (context);
41+ CGColorSpaceRelease (colorSpace);
42+
43+ return pixels;
44+ }
45+
46+ - (CGFloat)g8_similarityWithImage : (UIImage *)image
47+ {
1948 if (CGSizeEqualToSize (self.size , image.size ) == NO ) {
20- return NO ;
49+ return 0.0 ;
2150 }
2251
23- NSData *data = [image g8_normalizedData ];
24- NSData *originalData = [self g8_normalizedData ];
25- return [originalData isEqualToData: data];
52+ CGSize size = [self size ];
53+ int width = size.width ;
54+ int height = size.height ;
55+
56+ uint32_t *p1 = [self pixels ];
57+ uint32_t *p2 = [image pixels ];
58+
59+ NSInteger numDifferences = 0 ;
60+ NSInteger totalCompares = width * height;
61+
62+ for (int y = 0 ; y < height; y++) {
63+ for (int x = 0 ; x < width; x++) {
64+ if (p1[y * width + x] != p2[y * width + x]) {
65+ ++numDifferences;
66+ }
67+ }
68+ }
69+
70+ free (p1);
71+ free (p2);
72+
73+ return 1.0 - (CGFloat)numDifferences / totalCompares;
2674}
2775
28- - (NSData *)g8_normalizedData
76+ - (UIImage *)g8_normalizedImage
2977{
3078 const CGSize pixelSize = CGSizeMake (self.size .width * self.scale , self.size .height * self.scale );
3179 UIGraphicsBeginImageContext (pixelSize);
@@ -34,7 +82,7 @@ - (NSData *)g8_normalizedData
3482
3583 UIImage *drawnImage = UIGraphicsGetImageFromCurrentImageContext ();
3684 UIGraphicsEndImageContext ();
37- return UIImagePNGRepresentation ( drawnImage) ;
85+ return drawnImage;
3886}
3987
4088- (BOOL )g8_isFilledWithColor : (UIColor *)color
0 commit comments