[英]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
. 基本上我想做的就是比较一个
layer.fillColor
的CGColor
和UIColor.black.cgColor
。
The function CGColorEqualToColor
is now deprecated in Swift 4. 函数
CGColorEqualToColor
现在在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.
我猜他们必须有相同的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:) CGColor
有一个方法转换(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. 这是
CGColor
的扩展,用于检查给定颜色是否为黑色。 This works with colors in the RGB and greyscale color spaces. 这适用于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())
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. 我建议将2种颜色转换为字符串然后比较正常。 To convert them to strings, there is an answer for that https://stackoverflow.com/a/14051861/3342901 .
要将它们转换为字符串,可以找到https://stackoverflow.com/a/14051861/3342901的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.