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.
+ (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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With