Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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

This comment has been minimized.

Show comment Hide comment
@edelabar

edelabar Feb 16, 2015

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

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

@shallad

This comment has been minimized.

Show comment Hide comment
@shallad

shallad 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.

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