1

我有一个输入 RGV 值的 NSColorPanel:

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

关于我做错了什么的任何建议?

4

1 回答 1

2

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

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

在此处输入图像描述

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

  • 当人们互相说十六进制代码时,几乎普遍认为它表示与 HTML/CSS 产生的颜色相同。这意味着十六进制代码必须在 sRGB 颜色空间中,因为 Web 标准规定,只要颜色空间信息被忽略/丢失,就必须使用 sRGB。
  • Apple 的“通用 RGB”(NSCalibratedRGBColorSpace)与大多数现代显示器的 sRGB 和原生色彩空间有很大不同。您的问题只是说明了这种差异有多大。
  • 世界上大多数显示器的制造都尽可能匹配 sRGB,而现代 Apple 设备的高品质显示器尤其擅长这一点。
  • 这导致了一些令人惊讶的结论:如果需要这些十六进制代码来产生与 HTML 中相同的颜色,使用NSDeviceRGBColorSpace, 但是错误的是,而不是NSCalibratedRGBColorSpace提供更好的结果。您可以通过在 Device、Generic 和 sRGB 颜色空间中输入相同的颜色坐标并与 Safari 中生成的 HTML 页面进行比较来轻松验证这一事实。
  • 如果您需要与 Web 中使用的十六进制代码进行正确且有保证的匹配,则必须手动将颜色转换为 sRGB,因为NSColor不支持读取除设备 RGB 和校准 RGB 之外的任何颜色配置文件的组件。
于 2014-09-13T12:30:35.620 回答