我有一个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
关于我做错了什么建议?
答案 0 :(得分:2)
您必须在不同颜色空间(可能是设备)中输入坐标,因为在我的Mac上,当转换为校准色彩空间时,我的显示器的色彩空间中的#4272AA产生几乎相同的结果,#345C9A。
要更改NSColorPanel
中的色彩空间,请单击小彩虹按钮。 NSCalibratedRGBColorSpace
对应于“Generic RGB”选择 - 由于你的get-hex方法使用了校准,如果你想要获得相同的数字,你需要使用相同的。
一点点警告:developer.apple.com的这段代码是有害的。
NSDeviceRGBColorSpace
,但是错误的是,而不是NSCalibratedRGBColorSpace
会产生更好的结果< / em>的。您可以通过在Device,Generic和sRGB颜色空间中输入相同的颜色坐标并与Safari生成的HTML页面进行比较来轻松验证这一事实。NSColor
不支持读取除设备RGB和校准RGB之外的任何颜色配置文件的组件