How to compare UIColors?

Viewed 54487

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.

20 Answers

Have you tried [myColor isEqual:someOtherColor] ?

This UIColor extension works fine provided that the compared colors can be converted into RGB format, which should be most of the cases.

public extension UIColor {

    static func == (l: UIColor, r: UIColor) -> Bool {
        var l_red = CGFloat(0); var l_green = CGFloat(0); var l_blue = CGFloat(0); var l_alpha = CGFloat(0)
        guard l.getRed(&l_red, green: &l_green, blue: &l_blue, alpha: &l_alpha) else { return false }
        var r_red = CGFloat(0); var r_green = CGFloat(0); var r_blue = CGFloat(0); var r_alpha = CGFloat(0)
        guard r.getRed(&r_red, green: &r_green, blue: &r_blue, alpha: &r_alpha) else { return false }
        return l_red == r_red && l_green == r_green && l_blue == r_blue && l_alpha == r_alpha
    }
}

At least with this extension:

UIColor.whiteColor == UIColor(hex: "#FFFFFF") // true
UIColor.black == UIColor(red: 0, green: 0, blue: 0, alpha: 1) // true

Both comparisons would return false if compared using the native UColor.isEqual(...)

I have a similar but polished and cleaner answer that is easy to read and use:

extension UIColor {
   var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
       var red = CGFloat.zero
       var green = CGFloat.zero
       var blue = CGFloat.zero
       var alpha = CGFloat.zero
    
       guard getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
           debugPrint("color could not be retrieved")
           return (1.0, 1.0, 1.0, 1.0)
       }
       return (red, green, blue, alpha)
   }

   static func == (lhs: UIColor, rhs: UIColor) -> Bool {
       return  lhs.rgba == rhs.rgba
   }
}

you can use it like this: (quote from boherna)

UIColor.whiteColor == UIColor(hex: "#FFFFFF") // true
UIColor.black == UIColor(red: 0, green: 0, blue: 0, alpha: 1) // true

UIColor extension

- (CGFloat)accuracyCompareWith:(UIColor *)color {
    CIColor *c1 = [[CIColor alloc] initWithColor:self];
    CIColor *c2 = [[CIColor alloc] initWithColor:color];

    BOOL hasAlpha = c1.numberOfComponents == 4 && c2.numberOfComponents == 4;
    NSInteger numberOfComponents = hasAlpha ? 4 : 3;

    CGFloat colorMax = 1.0;
    CGFloat p = colorMax / 100.0;

    CGFloat redP = fabs(c1.red / p - c2.red / p);
    CGFloat greenP = fabs(c1.green / p - c2.green / p);
    CGFloat blueP = fabs(c1.blue / p - c2.blue / p);
    CGFloat alphaP = 0;

    if (hasAlpha)
        alphaP = fabs(c1.alpha / p - c2.alpha / p);

    return (redP + greenP + blueP + alphaP) / (CGFloat)numberOfComponents;
}

Why not add the extension with equatable protocol? This answer is using the solution of Nicolas Miari. So, if you like this answer, please be welcome to like his answer (second from the top)

The comment of Zoul: Be careful when comparing colors this way, because they have to be in the same color model to be considered equal. For instance, #ffffff does not equal [UIColor whiteColor]

static func == (lhs: UIColor, rhs: UIColor) -> Bool {

    let colorSpaceRGB = CGColorSpaceCreateDeviceRGB()
    let convertColorToRGBSpace: ((UIColor) -> UIColor?) = { (color) -> UIColor? in
        guard color.cgColor.colorSpace?.model == .monochrome else {
            return color
        }
        guard let oldComponents = color.cgColor.components else {
            return nil
        }
        let newComponents = [oldComponents[0], oldComponents[0], oldComponents[0], oldComponents[1]]
        guard let colorRef = CGColor(colorSpace: colorSpaceRGB, components: newComponents) else {
            return nil
        }
        return UIColor(cgColor: colorRef)
    }

    guard let selfColor = convertColorToRGBSpace(lhs),
        let otherColor = convertColorToRGBSpace(rhs) else {
            return false
    }
    return selfColor.isEqual(otherColor)
}

While @samvermette's answer is very good, I've found that it can sometimes lead to false negatives when comparing different color types (in my case UIDeviceRGBColor to UICachedDeviceWhiteColor). I fixed it by explicitly creating the color in the `else', too:

- (BOOL)isEqualToColor:(UIColor *)otherColor
{
    if (self == otherColor)
        return YES;

    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
        {
            const CGFloat *oldComponents = CGColorGetComponents(color.CGColor);
            CGFloat components[4] = {oldComponents[0], oldComponents[1], oldComponents[2], oldComponents[3]};
            CGColorRef colorRef = CGColorCreate(colorSpaceRGB, components);
            UIColor *color = [UIColor colorWithCGColor:colorRef];
            CGColorRelease(colorRef);
            return color;
        }
    };

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

    return [selfColor isEqual:otherColor];
}

You have to use

BOOL equalColors = CGColorEqualToColor(uiColor1.CGColor, uiColor2.CGColor));

Documentation here.

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