Convert Hex Color Code to NSColor
Here is two very useful macros
#define RGBA(r,g,b,a) [NSColor colorWithCalibratedRed:r/255.f green:g/255.f blue:b/255.f alpha:a/255.f]
#define NSColorFromRGB(rgbValue) [NSColor colorWithCalibratedRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
Here's the swift 2 compatible version of Zlatan's answer above (and +1 to him!):
func getColorFromString(webColorString : String) -> NSColor?
{
var result : NSColor? = nil
var colorCode : UInt32 = 0
var redByte, greenByte, blueByte : UInt8
// these two lines are for web color strings that start with a #
// -- as in #ABCDEF; remove if you don't have # in the string
let index1 = webColorString.endIndex.advancedBy(-6)
let substring1 = webColorString.substringFromIndex(index1)
let scanner = NSScanner(string: substring1)
let success = scanner.scanHexInt(&colorCode)
if success == true {
redByte = UInt8.init(truncatingBitPattern: (colorCode >> 16))
greenByte = UInt8.init(truncatingBitPattern: (colorCode >> 8))
blueByte = UInt8.init(truncatingBitPattern: colorCode) // masks off high bits
result = NSColor(calibratedRed: CGFloat(redByte) / 0xff, green: CGFloat(greenByte) / 0xff, blue: CGFloat(blueByte) / 0xff, alpha: 1.0)
}
return result
}
+ (NSColor*)colorWithHexColorString:(NSString*)inColorString
{
NSColor* result = nil;
unsigned colorCode = 0;
unsigned char redByte, greenByte, blueByte;
if (nil != inColorString)
{
NSScanner* scanner = [NSScanner scannerWithString:inColorString];
(void) [scanner scanHexInt:&colorCode]; // ignore error
}
redByte = (unsigned char)(colorCode >> 16);
greenByte = (unsigned char)(colorCode >> 8);
blueByte = (unsigned char)(colorCode); // masks off high bits
result = [NSColor
colorWithCalibratedRed:(CGFloat)redByte / 0xff
green:(CGFloat)greenByte / 0xff
blue:(CGFloat)blueByte / 0xff
alpha:1.0];
return result;
}
It doesn't take alpha values into account, it assumes values like "FFAABB", but it would be easy to modify.