简体   繁体   中英

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?

CGColor has a method converted(to:intent:options:)

So maybe you could have a method as follows:

extension CGColor
{
    func compareConvertingColorSpace(other: CGColor) -> Bool 
    {
        let approximateColor = other.converted(to: self.colorSpace! intent: .defaultIntent, options nil) // fatal errror with no color space
        return self == approximateColor 
    }
}

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
}

I would suggest to convert the 2 colours to Strings and then compare them normal. To convert them to strings, there is an answer for that https://stackoverflow.com/a/14051861/3342901 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM