SKShapeNode.fillColor不等于原始UIColor

时间:2018-10-06 19:19:57

标签: ios swift sprite-kit uicolor skshapenode

我刚刚浪费了很多时间寻找答案,为什么下面的代码给出的结果不相等:

let originalColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
let section = SKShapeNode(path: path.cgPath)
section.fillColor = originalColor
let isEqual = section.fillColor == originalColor //=> gives false

我没有任何想法,这有什么问题。我已经比较了色彩空间和UIColor对应的CGColor,只有CGColor具有不同的hashValue。但是为什么呢?上面的代码应该正常工作,非常简单,我在这里缺少什么?

编辑 我已使用以下代码比较UIColor

extension SKColor {

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

func isEqualTo(_ color: UIColor) -> Bool {
    var red1: CGFloat = 0, green1: CGFloat = 0, blue1: CGFloat = 0, alpha1: CGFloat = 0
    getRed(&red1, green:&green1, blue:&blue1, alpha:&alpha1)

    var red2: CGFloat = 0, green2: CGFloat = 0, blue2: CGFloat = 0, alpha2: CGFloat = 0
    color.getRed(&red2, green:&green2, blue:&blue2, alpha:&alpha2)

    return red1 == red2 && green1 == green2 && blue1 == blue2 && alpha1 == alpha2
}

}

其他UIColor的比较结果-用相同的方式实例化(后缀为1的红色/绿色/蓝色是形状的fillColor

(lldb) po red1
0.8784313797950745

(lldb) po red2
0.8784313725490196

(lldb) po green1
0.10196078568696976

(lldb) po green2
 0.10196078431372549

(lldb) po blue1
0.30980393290519714

(lldb) po blue2
0.30980392156862746

1 个答案:

答案 0 :(得分:1)

尝试更改此内容:

return red1 == red2 && green1 == green2 && blue1 == blue2 && alpha1 == alpha2

对此:

return Float(red1) == Float(red2) && 
    Float(green1) == Float(green2) && 
    Float(blue1) == Float(blue2) && 
    Float(alpha1) == Float(alpha2)