Search code examples
swiftmacoscocoanscolor

Swift - why NSColor becomes lighter when rendered


I've created NSWindow and made it's background colour absolutely blue (#0000FF). But when the window is rendered, the colour is "lighter" than it should be (#0F3FFB).

class LilWindow: NSViewController {
   override func viewDidLoad() {
        self.view.window?.backgroundColor = 
             NSColor.init(red: 0, green: 0, blue: 1, alpha: 1)


}

Does anyone know why it is happening and how to fix this? (screenshot attached)

enter image description here


Solution

  • Okay, so after a couple of hours fiddling with code and @KenThomases help, I figured out that if you want your RGB colours to looks correctly on NSImages and NSWindows, you must convert it into NSDeviceRGBColorSpace colorspace. To do this I've written a simple function:

    func toScreenColor(color:NSColor) -> NSColor {
      var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
    
      color
      .colorUsingColorSpaceName(NSCalibratedRGBColorSpace)!
      .getRed(&red, green: &green, blue: &blue, alpha: &alpha)
    
      return NSColor(deviceRed: red, green: green, blue: blue, alpha: alpha)
    }