|
Q: How do I get the hexadecimal value of an NSColor object?A: Below are the steps required to get the hexadecimal value of an NSColor object.
Listing 1 shows how to programmatically implement these steps; it builds an Objective-C Listing 1: Adding a category to NSColor. #import <Cocoa/Cocoa.h> @interface NSColor(NSColorHexadecimalValue) -(NSString *)hexadecimalValueOfAnNSColor; @end @implementation NSColor(NSColorHexadecimalValue) -(NSString *)hexadecimalValueOfAnNSColor { float redFloatValue, greenFloatValue, blueFloatValue; int redIntValue, greenIntValue, blueIntValue; NSString *redHexValue, *greenHexValue, *blueHexValue; //Convert the NSColor to the RGB color space before we can access its components NSColor *convertedColor=[self colorUsingColorSpaceName:NSCalibratedRGBColorSpace]; if(convertedColor) { // Get the red, green, and blue components of the color [convertedColor getRed:&redFloatValue green:&greenFloatValue blue:&blueFloatValue alpha:NULL]; // Convert the components to numbers (unsigned decimal integer) between 0 and 255 redIntValue=redFloatValue*255.99999f; greenIntValue=greenFloatValue*255.99999f; blueIntValue=blueFloatValue*255.99999f; // Convert the numbers to hex strings redHexValue=[NSString stringWithFormat:@"%02x", redIntValue]; greenHexValue=[NSString stringWithFormat:@"%02x", greenIntValue]; blueHexValue=[NSString stringWithFormat:@"%02x", blueIntValue]; // Concatenate the red, green, and blue components' hex strings together with a "#" return [NSString stringWithFormat:@"#%@%@%@", redHexValue, greenHexValue, blueHexValue]; } return nil; } @end Listing 2: Getting the hexadecimal value of an NSColor object. //aColor is an NSColor object NSString *hexValue=[aColor hexadecimalValueOfAnNSColor]; Further ReadingDocument Revision History
Posted: 2007-12-19 |
|