Created
May 16, 2012 05:41
-
-
Save acwright/2707798 to your computer and use it in GitHub Desktop.
NSColor+Hex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.