1

我有一个 NSColor,我真的想要它代表的 32 位 RGBA 值。有没有什么简单的方法可以得到这个,除了提取浮点组件,然后乘法和 ORing 并且通常做粗鲁的、依赖于字节序的事情吗?

编辑:感谢您的帮助。真的,我希望的是 Cocoa 功能已经做到了这一点,但我自己做这件事很酷。

4

3 回答 3

5

另一种更暴力的方法是创建一个临时的 CGBitmapContext 并填充颜色。

NSColor *someColor = {whatever};
uint8_t data[4];

CGContextRef ctx = CGBitmapContextCreate((void*)data, 1, 1, 8, 4, colorSpace, kCGImageAlphaFirst | kCGBitmapByteOrder32Big);

CGContextSetRGBFillColor(ctx, [someColor redComponent], [someColor greenComponent], [someColor blueComponent], [someColor alphaComponent]);

CGContextFillRect(ctx, CGRectMake(0,0,1,1));

CGContextRelease(ctx);

FWIW,每个组件颜色值 8 位不存在字节序问题。字节顺序仅适用于 16 位或更大的整数。您可以按照您想要的任何方式布置内存,但是无论是大端还是小端机器,8 位整数值都是相同的。(我相信 ARGB 是 Core Graphics 和 Core Image 的默认 8 位格式)。

为什么不只是这个?:

uint32_t r = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor redComponent])) * 255.0f);
uint32_t g = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor greenComponent])) * 255.0f);
uint32_t b = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor blueComponent])) * 255.0f);
uint32_t a = (uint32_t)(MIN(1.0f, MAX(0.0f, [someColor alphaComponent])) * 255.0f);
uint32_t value = (r << 24) | (g << 16) | (b << 8) | a;

然后你就知道它在内存中是如何布局的了。

或者这个,如果你更清楚的话:

uint8_t r = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor redComponent])) * 255.0f);
uint8_t g = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor greenComponent])) * 255.0f);
uint8_t b = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor blueComponent])) * 255.0f);
uint8_t a = (uint8_t)(MIN(1.0f, MAX(0.0f, [someColor alphaComponent])) * 255.0f);

uint8_t data[4];
data[0] = r;
data[1] = g;
data[2] = b;
data[3] = a;
于 2008-11-26T22:55:44.673 回答
3

并非所有颜色都有RGBA 表示。它们可能在 RGBA 中有一个近似值,但这可能准确也可能不准确。此外,Core Graphics 将“颜色”绘制为图案(例如,某些 Mac OS X 版本上的窗口背景颜色)。

于 2008-11-26T22:53:34.227 回答
1

将 4 个浮点数转换为它们的整数表示,但是你想实现它,是唯一的方法。

于 2008-11-26T22:19:21.613 回答