Objective-c – Convert Hex Color Code to NSColor

cocoamacosobjective c

I am having some trouble converting a a hexcode to an NSColor. Note this is for a Mac App (hence the NSColor instead of UIColor). This is the code I have so far:

- (NSColor *) createNSColorFromString:(NSString *)string {
NSString* hexNum = [string substringFromIndex:1];
NSColor* color = nil;
unsigned int colorCode = 0;
unsigned char red, green, blue;
if (string) {
    NSScanner* scanner = [NSScanner scannerWithString:hexNum];
    (void) [scanner scanHexInt:&colorCode];
}
red = (unsigned char) (colorCode >> 16);
green = (unsigned char) (colorCode >> 8);
blue = (unsigned char) (colorCode);
color = [NSColor colorWithCalibratedRed:(float)red / 0xff green:(float)green / 0xff blue:(float)blue / 0xff alpha:1.0];
return color;

}

Any help would be appreciated.

Best Answer

+ (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.