15
votes

How do I create a NSColor from a RGB value?

4

4 Answers

17
votes

Per the NSColor documentation:

NSColor *myColor = [NSColor colorWithCalibratedRed:redValue green:greenValue blue:blueValue alpha:1.0f];
11
votes

Also don't forget to do the following conversion from the actual RGB values you get, lets say from Photoshop...

an RGB of (226, 226, 226) could be instantiated as a NSColor using the values:

Red:   226/255 = 0.886... 
Green: 226/255 = 0.886...
Blue:  226/255 = 0.886... 

[NSColor colorWithDeviceRed:0.886f green:0.886f blue:0.886f alpha:1.0f];

Why 255? 8-bit color channels range from 0 to 255 (inclusive). When normalized this is scaled to the range [0,1] (inclusive). See references for conversions from normalized values to unnormalized values and vice versa.

References

4
votes
float red = 0.5f;
float green = 0.2f;
float blue = 0.4f;
float alpha = 0.8f;

NSColor *rgb = [NSColor colorWithDeviceRed:red green:green blue:blue alpha:alpha];
-3
votes

Extension for Swift 2

extension NSObject {
    func RGB(r:CGFloat, g:CGFloat, b:CGFloat, alpha:CGFloat? = 1) -> NSColor {
        return NSColor(red: r/255, green: g/255, blue: b/255, alpha: alpha!)
    }
}

Then just call

RGB(r: 16, g: 105, b: 125)

or

RGB(r: 16, g: 105, b: 125, alpha: 0.5)