Skip to content

Instantly share code, notes, and snippets.

@eric-robinson
Created January 11, 2012 05:26
Show Gist options
  • Save eric-robinson/1593197 to your computer and use it in GitHub Desktop.
Save eric-robinson/1593197 to your computer and use it in GitHub Desktop.
Hex string to NSColor
@interface NSString(ColorAdditions)
-(NSColor*)hexStringToNSColor;
@end
@implementation NSString(ColorAdditions)
-(NSColor *) hexStringToNSColor {
unsigned int c;
if ([self characterAtIndex:0] == '#') {
if([self length] != 7) {
return nil;
}
[[NSScanner scannerWithString:[self substringFromIndex:1]] scanHexInt:&c];
}
else {
if([self length] != 6) {
return nil;
}
[[NSScanner scannerWithString:self] scanHexInt:&c];
}
return [NSColor colorWithDeviceRed:((c & 0xff0000) >> 16)/255.0
green:((c & 0xff00) >> 8)/255.0
blue:(c & 0xff)/255.0 alpha:1.0];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment