Search code examples
swiftmacoscocoaswift3nscolor

Creating CGColor from RGB Value


I use the following code to set the background of a viewcontroller

    view.wantsLayer = true
    let myColor = NSColor(calibratedRed: 50, green: 50, blue: 50, alpha: 1.0)
    view.layer?.backgroundColor = myColor.cgColor

But on debugging myColor i get the following color instead of the intended color

enter image description here


Solution

  • Here is the documentation. Anything above 1 is considered as 1. You need to divide each value by 255.

    view.wantsLayer = true
    let myColor = NSColor(calibratedRed: 50/255, green: 50/255, blue: 50/255, alpha: 1.0)
    view.layer?.backgroundColor = myColor.cgColor
    

    Also, check this out -> Link