nscolornscolorpanel

NSColorPanel to hex issue?


I have an NSColorPanel that I am inputting RGV values:

NSColorPanel * sharedPanel = [NSColorPanel sharedColorPanel];
[sharedPanel setTarget: self];
[sharedPanel setAction: updateColor:];
[sharedPanel orderFront: self];

The color panel display and I set this value: r66, g114, b170

By my calculations, this should be #4272AA. I use the following code to convert to hex:

- (void) updateColor: (NSColorPanel*) panel
{
    NSString * hexString = [panel.color hexadecimalValueOfAnNSColor];
    NSLog(@"%@", hexString);
}

Which logs out #345d9a (not what I would expect).

I'm using the following method from directly from developer.apple.com to convert the color to hex:

#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

Any suggestions as to what I'm doing wrong?


Solution

  • You must have entered coordinates in different color space (probably device's, since on my Mac, #4272AA in color space of my display when converted to calibrated color space produces almost the same result, #345C9A).

    To change color space in NSColorPanel, click tiny rainbow button. NSCalibratedRGBColorSpace corresponds to "Generic RGB" selection — since your get-hex method uses calibrated, you need to use the same if you want to get the same numbers back.

    enter image description here

    A tiny bit of warning: this piece of code from developer.apple.com is harmful.