Creating CGColor from RGB Value

271 Views Asked by At

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

2

There are 2 best solutions below

0
Frankenstein On BEST ANSWER

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

1
Jawad Ali On

Range of color components (RGBA) vary between [0,1]

init(red:green:blue:alpha:)

Creates a color object with the specified red, green, blue, and alpha channel values. This method accepts extended color component values. If the red, green, blue, or alpha values are outside of the 0-1.0 range,

So you can get cgColor

view.layer?.backgroundColor = NSColor(calibratedRed: 50.0/255.0, green: 50.0/255.0, blue: 50.0/255.0, alpha: 1.0).cgColor