Aarhus88
Aarhus88

Reputation: 161

Save NSColor components to file

I am trying to save an instance of NSColor to a file like this:

  writeF(node.lineColour.hueComponent)
  writeF(node.lineColour.saturationComponent)
  writeF(node.lineColour.brightnessComponent)
  writeF(node.lineColour.alphaComponent)

where the write function is:

  func writeF(var val: CGFloat) -> Bool {    
    let nsd = NSData(bytes: &val, length: sizeof(CGFloat))
    let rv = oStream!.write(UnsafePointer(nsd.bytes), maxLength: sizeof(CGFloat))
    return rv > 0
  }

And "node.lineColour" is just NSColor.blueColor(). It all compiles OK, but gives a run-time message at the first "writeF" line:

2015-10-01 07:57:43.871 canl[77917:8371660] An uncaught exception was raised 2015-10-01 07:57:43.871 canl[77917:8371660] *** -hueComponent not valid for the NSColor NSCalibratedWhiteColorSpace 0 1; need to first convert colorspace.

Apple documentation on color spaces is very esoteric (if you already understand it then it's a fine reference, but if not then... good luck). Why is the above code wrong? Should be able to at least retrieve the color components (CGFloat).

Upvotes: 0

Views: 605

Answers (1)

Aarhus88
Aarhus88

Reputation: 161

After swimming through the available documentation and trying different things, I found this to work:

  let aColor = node.lineColor.colorUsingColorSpaceName(NSCalibratedRGBColorSpace)

  if let culoare = aColor {
    writeF(culoare.redComponent)
    writeF(culoare.greenComponent)
    writeF(culoare.blueComponent)
    writeF(culoare.alphaComponent)
  }

It also works for getting the hue, saturation, and brightness components, but I think I will go with RGB.

Upvotes: 2

Related Questions