创建具有RGB值的NSColor

时间:2009-12-21 05:27:11

标签: objective-c cocoa rgb

如何从RGB值创建NSColor?

4 个答案:

答案 0 :(得分:16)

根据NSColor文档:

NSColor *myColor = [NSColor colorWithCalibratedRed:redValue green:greenValue blue:blueValue alpha:1.0f];

答案 1 :(得分:8)

另外,请不要忘记从您获得的实际RGB值进行以下转换,让我们说从Photoshop ...

RGB(226,226,226)可以使用以下值实例化为NSColor:

Red:   226/255 = 0.886... 
Green: 226/255 = 0.886...
Blue:  226/255 = 0.886... 

[NSColor colorWithDeviceRed:0.886f green:0.886f blue:0.886f alpha:1.0f];

为什么是255? 8位颜色通道的范围为0到255(含)。归一化时,将其缩放到[0,1](含)范围。请参阅参考文献,了解从标准化值到非标准化值的转换,反之亦然。

参考

答案 2 :(得分:4)

float red = 0.5f;
float green = 0.2f;
float blue = 0.4f;
float alpha = 0.8f;

NSColor *rgb = [NSColor colorWithDeviceRed:red green:green blue:blue alpha:alpha];

答案 3 :(得分:-3)

Swift 2的扩展程序

extension NSObject {
    func RGB(r:CGFloat, g:CGFloat, b:CGFloat, alpha:CGFloat? = 1) -> NSColor {
        return NSColor(red: r/255, green: g/255, blue: b/255, alpha: alpha!)
    }
}

然后致电

RGB(r: 16, g: 105, b: 125)

RGB(r: 16, g: 105, b: 125, alpha: 0.5)