我有一个输入RGV值的NSColorPanel:
NSColorPanel * sharedPanel = [NSColorPanel sharedColorPanel];
[sharedPanel setTarget: self];
[sharedPanel setAction: updateColor:];
[sharedPanel orderFront: self];显示的彩色面板和我设置的值: r66、g114、b170
根据我的计算,这应该是#4272 be。我使用以下代码将其转换为十六进制:
- (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对我做错了什么有什么建议吗?
发布于 2014-09-13 12:30:35
您必须在不同的颜色空间中输入坐标(可能是设备的,因为在我的Mac上,我的显示器的颜色空间中的#4272 in转换为校准的颜色空间时产生的结果几乎相同,#345C9A)。
若要更改NSColorPanel中的颜色空间,请单击“小彩虹”按钮。NSCalibratedRGBColorSpace对应于“泛型RGB”选择-由于您的get -十六进制方法使用校准,您需要使用相同的数字,如果您想要得到相同的数字。

一点警告:这段来自developer.apple.com的代码是有害的。
NSDeviceRGBColorSpace__,不管这是错误的,而不是NSCalibratedRGBColorSpace,都会得到更好的结果。通过在设备、泛型和sRGB颜色空间中输入相同的颜色坐标并与Safari中的HTML页面进行比较,您可以很容易地验证这一事实。NSColor不支持读取除设备RGB和校准的RGB之外的任何颜色配置文件的组件。https://stackoverflow.com/questions/24207313
复制相似问题