Instantly share code, notes, and snippets.

What would you like to do?
#import <Cocoa/Cocoa.h>
@interface NSColor (Hex)
- (NSString *)hexadecimalValue;
+ (NSColor *)colorFromHexadecimalValue:(NSString *)hex;
#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];

This comment has been minimized.

edelabar commented Feb 16, 2015

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


This comment has been minimized.

shallad commented Jul 8, 2015
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