Reputation: 177
I'm trying to compare two colors but I can't get the correct result:
Here is my code:
NSLog(@"selfColor = %@",selfColor);
NSLog(@"left = %@",left);
NSLog(@"[selfColor isEqual:left] = %@",[selfColor isEqual:left] ? @"TRUE":@"FALSE");
And here is my debug log:
2016-01-05 16:58:24.050 breakout[84467:11799727] selfColor = UIDeviceRGBColorSpace 0.333333 0.333333 0.333333 1
2016-01-05 16:58:24.050 breakout[84467:11799727] left = UIDeviceRGBColorSpace 0.333333 0.333333 0.333333 1
2016-01-05 16:58:24.050 breakout[84467:11799727] [selfColor isEqual:left] = FALSE
The two colors are the same, but the isEqual: function still return false... What am I missing ?
Thanks for your help
Edit:
The colors are generated by this function from another SO question
BOOL isEqualToColor(UIColor *left, UIColor *right) {
CGColorSpaceRef colorSpaceRGB = CGColorSpaceCreateDeviceRGB();
UIColor *(^convertColorToRGBSpace)(UIColor*) = ^(UIColor *color) {
if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) == kCGColorSpaceModelMonochrome) {
const CGFloat *oldComponents = CGColorGetComponents(color.CGColor);
CGFloat components[4] = {oldComponents[0], oldComponents[0], oldComponents[0], oldComponents[1]};
CGColorRef colorRef = CGColorCreate( colorSpaceRGB, components );
UIColor *color = [UIColor colorWithCGColor:colorRef];
CGColorRelease(colorRef);
return color;
} else
return color;
};
UIColor *selfColor = convertColorToRGBSpace(right);
left = convertColorToRGBSpace(left);
CGColorSpaceRelease(colorSpaceRGB);
NSLog(@"selfColor = %@",selfColor);
NSLog(@"left = %@",left);
NSLog(@"[selfColor isEqual:left] = %@",[selfColor isEqual:left] ? @"TRUE":@"FALSE");
return [selfColor isEqual:left];
}
And I call it like this:
if (isEqualToColor(node.color,[UIColor darkGrayColor])) {...}
Upvotes: 1
Views: 174
Reputation: 3422
Here is a way to compare colors
-(BOOL)isColor:(UIColor *)first similarToColor:(UIColor *)second {
float tolerance = 0.01; // 1%
CGColorRef firstColor = [first CGColor];
CGColorRef secondColor = [second CGColor];
if (CGColorGetColorSpace(firstColor) != CGColorGetColorSpace(secondColor)) {
return FALSE;
}
NSUInteger componentCount = CGColorGetNumberOfComponents(firstColor);
const CGFloat *leftComponents = CGColorGetComponents(firstColor);
const CGFloat *rightComponents = CGColorGetComponents(secondColor);
for (int i = 0; i < componentCount; i++) {
float difference = leftComponents[i] / rightComponents[i];
if (fabs(difference - 1) > tolerance) {
return FALSE;
}
}
return TRUE;
}
And make the call
[self isColor:selfColor similarToColor:left];
You can change the tolerance
value if you want a test more or less accurate
Upvotes: 1