Skip to content

Instantly share code, notes, and snippets.

@acwright
Created May 16, 2012 05:41
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acwright/2707798 to your computer and use it in GitHub Desktop.
Save acwright/2707798 to your computer and use it in GitHub Desktop.
NSColor+Hex
#import <Cocoa/Cocoa.h>
@interface NSColor (Hex)
- (NSString *)hexadecimalValue;
+ (NSColor *)colorFromHexadecimalValue:(NSString *)hex;
@end
#import "NSColor+Hex.h"
@implementation NSColor (Hex)
- (NSString *)hexadecimalValue {
double redFloatValue, greenFloatValue, blueFloatValue;
int redIntValue, greenIntValue, blueIntValue;
NSString *redHexValue, *greenHexValue, *blueHexValue;
NSColor *convertedColor = [self colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
if(convertedColor) {
[convertedColor getRed:&redFloatValue green:&greenFloatValue blue:&blueFloatValue alpha:NULL];
redIntValue = redFloatValue*255.99999f;
greenIntValue = greenFloatValue*255.99999f;
blueIntValue = blueFloatValue*255.99999f;
redHexValue = [NSString stringWithFormat:@"%02x", redIntValue];
greenHexValue = [NSString stringWithFormat:@"%02x", greenIntValue];
blueHexValue = [NSString stringWithFormat:@"%02x", blueIntValue];
return [NSString stringWithFormat:@"#%@%@%@", redHexValue, greenHexValue, blueHexValue];
}
return nil;
}
+ (NSColor *)colorFromHexadecimalValue:(NSString *)hex {
if ([hex hasPrefix:@"#"]) {
hex = [hex substringWithRange:NSMakeRange(1, [hex length] - 1)];
}
unsigned int colorCode = 0;
if (hex) {
NSScanner *scanner = [NSScanner scannerWithString:hex];
(void)[scanner scanHexInt:&colorCode];
}
return [NSColor colorWithDeviceRed:((colorCode>>16)&0xFF)/255.0 green:((colorCode>>8)&0xFF)/255.0 blue:((colorCode)&0xFF)/255.0 alpha:1.0];
}
@end
@edelabar
Copy link

Should line 52 be colorWithCalibratedRed:green:blue:alpha since you're using the calibrated color space on line 20?

@shallad
Copy link

shallad commented Jul 8, 2015

http://stackoverflow.com/questions/12568450/whats-the-difference-between-colorwithsrgbred-vs-colorwithdevicered-vs-colorwit
This also recommends to use calibrated color space instead of device color space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment