Friday, April 27, 2012

How to compare UIColors?


I'd like to check the color set for a background on a UIImageView. I've tried:




if(myimage.backgroundColor == [UIColor greenColor]){
...}
else{
...}



but that doesn't work, even when I know the color is green, it always falls into the else part.



Also, is there a way to output the current color in the debug console.




p [myimage backgroundColor]



and




po [myimage backgroundColor]



don't work.


Source: Tips4all

3 comments:

  1. Have you tried [myColor isEqual:someOtherColor] ?

    ReplyDelete
  2. As zoul pointed out in the comments, isEqual: will return NO when comparing colors that are in different models/spaces (for instance #FFF with [UIColor whiteColor]). I wrote this UIColor extension that converts both colors to the same color space before comparing them:

    - (BOOL)isEqualToColor:(UIColor *)otherColor {
    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]};
    return [UIColor colorWithCGColor:CGColorCreate(colorSpaceRGB, components)];
    } else
    return color;
    };

    UIColor *selfColor = convertColorToRGBSpace(self);
    otherColor = convertColorToRGBSpace(otherColor);
    CGColorSpaceRelease(colorSpaceRGB);

    return [selfColor isEqual:otherColor];
    }

    ReplyDelete
  3. if([myimage.backgroundColor isEqual:[UIColor greenColor]])

    ReplyDelete