Search code examples
iosswiftcalayerswift4cgcolor

how to Compare two CGColor in swift 4


Basically all I want to do is to compare a layer.fillColor which is a CGColor with UIColor.black.cgColor.

The function CGColorEqualToColor is now deprecated in Swift 4.

I have tried:

if(layer.fillColor === UIColor.black.cgColor){
          return      
}

And it still doesn't work. I guess they must have the same kCGColorSpaceModel.

This is the output of each color in logs

<CGColor 0x1c02a15c0> [<CGColorSpace 0x1c02a0a20> (kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1; extended range)] ( 0 0 0 1 )
<CGColor 0x1c008e290> [<CGColorSpace 0x1c02a0f60> (kCGColorSpaceICCBased; kCGColorSpaceModelMonochrome; Generic Gray Gamma 2.2 Profile; extended range)] ( 0 1 )

What's the solution?


Solution

  • Here's an extension for CGColor that checks if the given color is black or not. This works with colors in the RGB and greyscale color spaces.

    extension CGColor {
        func isBlack() -> Bool {
            let count = numberOfComponents
            if count > 1 {
                if let components = components {
                    for c in 0..<components.count-1 { // skip the alpha component
                        // All components are 0 for black
                        if components[c] != 0.0 {
                            return false
                        }
                    }
    
                    return true
                }
            }
    
            return false
        }
    }
    
    print(UIColor.black.cgColor.isBlack())
    print(UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor.isBlack())
    

    You can use this as:

    if layer.fillColor.isBlack() {
        return
    }