Comparing colors in Objective-C

I am trying to determine if two colors are equivalent using code written in Objective-C.

I use this code snippet to determine if these two colors are equivalent (currently for debugging purposes)

NSLog(@"currentColor is %@", currentColor); NSLog(@"Adjacent Color is %@",[[buttonArray objectAtIndex:1] backgroundColor]); NSLog(@"%i",[[buttonArray objectAtIndex:1] backgroundColor]==currentColor); 

My console shows

 2009-10-20 00:27:10.814 colorGame[13588:207] currentColor is kCGColorSpaceModelRGB 0 0 1 1 2009-10-20 00:27:10.815 colorGame[13588:207] Adjacent Color is kCGColorSpaceModelRGB 0 0 1 1 2009-10-20 00:27:10.815 colorGame[13588:207] 0 

I can post more code if asked (I don't know if this is really necessary). The current color was originally identified as

 UIColor *currentColor; 

if this is any help.

I am sure that I am just doing the comparison incorrectly, and that there is probably a built-in method that can compare colors that I simply don’t know about.

+6
comparison objective-c colors iphone quartz-graphics
source share
3 answers
 @implementation UIColor (compare) - (BOOL) isEqualToColor:(UIColor *) otherColor { return CGColorEqualToColor(self.CGColor, otherColor.CGColor); } @end 

Keep in mind that two colors that look the same may or may not return TRUE, since the components are stored as floating, and they may differ by a value less than what the display hardware can resolve.

Also keep in mind that if they are defined in different color spaces, this method will never return TRUE.

+17
source share

objects should be compared using the isEqual: method, not == , which simply compares the pointer address

+11
source share

You check object pointers for equivalence, which will probably never return true. If you want to work with the actual color values, you need to get the CGColor base link.

+1
source share

All Articles