NSColorPanel到十六进制问题?

时间:2014-06-13 14:06:32

标签: nscolor nscolorpanel

我有一个NSColorPanel,我正在输入RGV值:

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

彩色面板显示我设置了这个值:r66,g114,b170

根据我的计算,这应该是#4272AA。我使用以下代码转换为十六进制:

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

注销#345d9a(不是我期望的那样)。

我直接从developer.apple.com使用以下方法将颜色转换为十六进制:

#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

关于我做错了什么建议?

1 个答案:

答案 0 :(得分:2)

您必须在不同颜色空间(可能是设备)中输入坐标,因为在我的Mac上,当转换为校准色彩空间时,我的显示器的色彩空间中的#4272AA产生几乎相同的结果,#345C9A。

要更改NSColorPanel中的色彩空间,请单击小彩虹按钮。 NSCalibratedRGBColorSpace对应于“Generic RGB”选择 - 由于你的get-hex方法使用了校准,如果你想要获得相同的数字,你需要使用相同的。

enter image description here

一点点警告:developer.apple.com的这段代码是有害的。

  • 当人们互相说十六进制代码时,几乎普遍认为它与HTML / CSS产生的颜色相同。这意味着十六进制代码必须是sRGB颜色空间,因为无论何时省略/丢失颜色空间信息,Web标准都要求使用sRGB。
  • Apple的“Generic RGB”(NSCalibratedRGBColorSpace)与sRGB和大多数现代显示器的原生色彩空间非常不同。你的问题只是证明了这种差异有多大。
  • 世界上大多数显示器的制造都尽可能地与sRGB相匹配,现代Apple设备的高质量显示效果特别好。
  • 这会产生一些令人惊讶的结论:如果需要这些十六进制代码来生成与HTML中相同的颜色,使用NSDeviceRGBColorSpace,但是错误的是,而不是NSCalibratedRGBColorSpace会产生更好的结果< / em>的。您可以通过在Device,Generic和sRGB颜色空间中输入相同的颜色坐标并与Safari生成的HTML页面进行比较来轻松验证这一事实。
  • 如果您需要与Web中使用的十六进制代码进行正确且有保证的匹配,则必须手动将颜色转换为sRGB,因为NSColor不支持读取除设备RGB和校准RGB之外的任何颜色配置文件的组件