iosswiftsprite-kituicolorskshapenode

SKShapeNode.fillColor not equal to original UIColor


I have just wasted many hours looking for an answer why below code gives not equal result:

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

I don't have any idea, what's wrong with that. I have compared the color spaces and UIColor's corresponding CGColor and only the CGColor has a different hashValue. But why is that? Above code should be working, it's pretty straightforward, what am I missing here?

EDIT I have used below code to compare UIColors:

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
}

}

The compare result for some other UIColor - instantiated the same way (red/green/blue with suffix 1 is the fillColor of the shape:

(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

Solution

  • Try changing this:

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

    To this:

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