【问题标题】:how to Compare two CGColor in swift 4如何在swift 4中比较两个CGColor
【发布时间】:2018-06-13 09:15:23
【问题描述】:

基本上我想做的就是将layer.fillColorCGColorUIColor.black.cgColor 进行比较。

函数 CGColorEqualToColor 现已在 Swift 4 中弃用。

我试过了:

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

它仍然不起作用。我猜他们必须有相同的 kCGColorSpaceModel。

这是日志中每种颜色的输出

<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 )

解决办法是什么?

【问题讨论】:

  • 实现color difference measure。如果你把自己限制在 RGB 或 sRGB,那很简单
  • CGColorEqualToColor== 存在相同的问题,因为它会检查色彩空间,因此如果不弃用它也无济于事。

标签: ios swift calayer swift4 cgcolor


【解决方案1】:

CGColor 有一个方法converted(to:intent:options:)

所以也许你可以有如下方法:

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 
    }
}

【讨论】:

    【解决方案2】:

    这是CGColor 的扩展,用于检查给定颜色是否为黑色。这适用于 RGB 和灰度颜色空间中的颜色。

    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())
    

    你可以这样使用:

    if layer.fillColor.isBlack() {
        return
    }
    

    【讨论】:

      【解决方案3】:

      我建议将 2 种颜色转换为字符串,然后正常比较它们。要将它们转换为字符串,https://stackoverflow.com/a/14051861/3342901 有一个答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-09
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 2016-08-11
        • 2018-11-15
        相关资源
        最近更新 更多