我有一个NSColor,我真的想要它代表的32位RGBA值.有没有什么简单的方法来获得这个,除了提取浮动组件,然后乘法和ORing,并通常做粗,依赖于endian的事情?
编辑:谢谢你的帮助.真的,我所希望的是一个Cocoa功能已经做到了这一点,但我自己很酷.
另一种更强力的方法是创建一个临时的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;