Comparing UIColors or CGColor or CGColorSpace

wiznaibus picture wiznaibus · May 22, 2011 · Viewed 11.1k times · Source

I'm having an issue comparing UIColors. I have an image, which I have successfully extracted the color on the image at which the user clicked. Now I want to compare that color with other colors, but I'm getting some strange results. Here's what I've tried:

    CGColorRef pixelColor = [[buttonImage colorAtPixel:point] CGColor];
UIColor* color = [UIColor colorWithCGColor:pixelColor];
UIColor* aqua = [UIColor colorWithRed:0.521569 green:0.768627 blue:0.254902 alpha:1];
if (CGColorEqualToColor(color.CGColor, aqua.CGColor)) {
    DLog(@"Apparently, it works");
}
DLog(@"%@", color.CGColor);
DLog(@"%@", aqua.CGColor);

Output:

2011-05-21 19:48:27.144 Coffee[66860:207] -[DescriptorsViewController touchesEnded:withEvent:] <CGColor 0x4d1eb80> [<CGColorSpace 0x4d1a070> (kCGColorSpaceDeviceRGB)] ( 0.521569 0.768627 0.254902 1 )
2011-05-21 19:48:27.145 Coffee[66860:207] -[DescriptorsViewController touchesEnded:withEvent:] <CGColor 0x4d1f750> [<CGColorSpace 0x4d1a070> (kCGColorSpaceDeviceRGB)] ( 0.521569 0.768627 0.254902 1 )

It looks like the CGColor addresses are different, but the CGColorSpaces are the same, but I can't figure out how to compare the CGColorSpaces

I've also tried this:

CGColorRef pixelColor = [[buttonImage colorAtPixel:point] CGColor];
UIColor* color = [UIColor colorWithCGColor:pixelColor];
UIColor* aqua = [UIColor colorWithRed:0.521569 green:0.768627 blue:0.254902 alpha:1];
if ([color isEqual:aqua]) {
    DLog(@"Apparently, it works");
}
DLog(@"%@", color.CGColor);
DLog(@"%@", aqua.CGColor);

The same silliness occurs.

2011-05-21 20:02:49.277 Coffee[67013:207] -[DescriptorsViewController touchesEnded:withEvent:] <CGColor 0x4d3b810> [<CGColorSpace 0x5912010> (kCGColorSpaceDeviceRGB)] ( 0.521569 0.768627 0.254902 1 )
2011-05-21 20:02:49.278 Coffee[67013:207] -[DescriptorsViewController touchesEnded:withEvent:] <CGColor 0x4d3ba20> [<CGColorSpace 0x5912010> (kCGColorSpaceDeviceRGB)] ( 0.521569 0.768627 0.254902 1 )`

Answer

artkoenig picture artkoenig · Feb 1, 2013

For CGColor you can use the function CGColorEqualToColor:

bool CGColorEqualToColor (
   CGColorRef color1,
   CGColorRef color2
);