Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Hex Color Code to NSColor

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.

like image 354
mdominick Avatar asked Jan 02 '12 03:01

mdominick


2 Answers

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

like image 125
Zlatan Avatar answered Sep 22 '22 22:09

Zlatan


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]
like image 28
serj Avatar answered Sep 23 '22 22:09

serj