objective-c 使用 RGB 值创建 NSColor

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1938365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:38:18  来源:igfitidea点击:

Creating a NSColor with RGB value

objective-ccocoargb

提问by nanochrome

How do I create a NSColor from a RGB value?

如何从 RGB 值创建 NSColor?

回答by Matt Ball

Per the NSColordocumentation:

根据NSColor文档:

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

回答by MiMo

Also don't forget to do the following conversion from the actual RGB values you get, lets say from Photoshop...

也不要忘记从您获得的实际 RGB 值进行以下转换,例如从 Photoshop...

an RGB of (226, 226, 226) could be instantiated as a NSColor using the values:

可以使用以下值将 (226, 226, 226) 的 RGB 实例化为 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];

Why 255? 8-bit color channels range from 0 to 255 (inclusive). When normalized this is scaled to the range [0,1] (inclusive). See references for conversions from normalized values to unnormalized values and vice versa.

为什么是255?8 位颜色通道的范围从 0 到 255(含)。归一化后,它会缩放到范围 [0,1](含)。请参阅有关从规范化值到非规范化值的转换的参考资料,反之亦然。

References

参考

回答by nash

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];

回答by emreoktem

Extension for Swift 2

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!)
    }
}

Then just call

然后就打电话

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

or

或者

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