CGColor to UIColor conversion
When I initialize a CGColor and convert it to UIColor it does not render in the same way as a UIColor that is initialized with the same values. How can I convert between CGColor and UIColor and keep the same appearance?
This code produces two slightly different colors (see screenshot) although I would expect the colors to be the same:
self.view.backgroundColor = UIColor(red: 19/255.0, green: 25/255.0, blue: 28/255.0, alpha: 1.0)
let myCGColor = CGColor(red: 19/255.0, green: 25/255.0, blue: 28/255.0, alpha: 1.0)
self.secondView.backgroundColor = UIColor(cgColor: myCGColor)
Top: UIColor / Bottom: CGColor->UIColor
Solution 1:
Thats because that CGColor initializer uses a different color space. UIColor uses extendedSRGB while CGColor uses Generic RGB.
If you want to get the same color you need to specify the same colorspace when initializing your CGColor:
let cgColor = CGColor(colorSpace: .init(name: CGColorSpace.extendedSRGB)!, components: [19.0/255, 25.0/255, 28.0/255, 1.0])!
For iOS13+ or macOS10.15+ you can use the init(srgbRed:green:blue:alpha:)
initializer:
let cgColor = CGColor(srgbRed: 19/255, green: 25/255, blue: 28/255, alpha: 1)