RGB values from NSColor

1.1k Views Asked by At

I'm attempting to read an osx colorlist (.clr), and having trouble interpreting the values of colors.

context: I'm writing a color palette plugin for a design program called Sketch. The plugins are written in cocoascript, which is a bridge between JS and Objective-C/Cocoa. This allows you to work with classes like NSColor

I'm using this code to read the file:

// Choose colorlist file ------------------------------------------

var openPanel = NSOpenPanel.openPanel();

openPanel.setCanChooseDirectories(true);
openPanel.setCanChooseFiles(true);
openPanel.setCanCreateDirectories(true);
openPanel.setTitle("Choose a file");
openPanel.setPrompt("Choose");
openPanel.runModal();

// Read colors from file ------------------------------------------

var filePath = openPanel.URLs().firstObject().path();
var fileName = filePath.lastPathComponent().stringByDeletingPathExtension();

var colorList = NSColorList.alloc().initWithName_fromFile(fileName, filePath);
var colorKeys = colorList.allKeys();
var color = colorList.colorWithKey(colorKeys[3]);    

log(color);

This works and I'm able to log the color to the OS X Console app. The problem is I'm not sure how to use the output:

NSCalibratedRGBColorSpace 0.0599575 0.220776 0.562826 1

the rgba value in CSS, Sketch, and Photoshop is

16, 77, 161, 1

I thought perhaps it just scaled the range from 255 to 1. But when I do the math it doesn't totally add up. The b value, for example:

0.562826 * 255 = 143.52063

but it should be 161.

Is there some other way I should be converting the color?

1

There are 1 best solutions below

0
On

Your color is a NSColor object, in NSCalibratedRGBColorSpace, which is standard RGB color space. You can covert it to integer values by official method.

https://developer.apple.com/library/mac/qa/qa1576/_index.html

I transform that to CocoaScript for you.

var red = color.redComponent() * 255.99999;
var green = color.greenComponent() * 255.99999;
var blue = color.blueComponent() * 255.99999;