ios 如何从 RGB 值中获取 cgcolor?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29466582/
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-08-31 05:30:39  来源:igfitidea点击:

how can i obtain a cgcolor from RGB values?

iosswiftrgbuicolorcgcolor

提问by alionthego

I'm trying to create a custom RGBCGColorusing swiftto use as a border color for a UIButton. I've tried following code but the color is not visible:

我试图创建一个自定义RGBCGColor使用swift的边框颜色的使用UIButton。我试过下面的代码,但颜色不可见:

var red = UIColor(red: 100.0, green: 130.0, blue: 230.0, alpha: 1.0)
self.layer.borderColor = red.CGColor

Is there any way to create a CGColordirectly from RGB values?

有没有办法CGColor直接从RGB值创建一个?

回答by Shruti

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

您必须给出介于 0 和 1.0 之间的值。因此,将 RGB 值除以 255。

Change Your code to

将您的代码更改为

var red = UIColor(red: 100.0/255.0, green: 130.0/255.0, blue: 230.0/255.0, alpha: 1.0)
self.layer.borderColor = red.CGColor

回答by Mick Stupp

You can get that down to one line in Swift 3:

您可以在 Swift 3 中将其缩减为一行:

avLayer.backgroundColor = UIColor.red.CGColor

回答by Romain

On Mac OS X there is CGColorCreateGenericRGB(), but it doesn't exist on iOS. You can use CGColorCreatewith appropriate parameters, though.

在 Mac OS X 上有CGColorCreateGenericRGB(),但在 iOS 上不存在。不过,您可以使用CGColorCreate适当的参数。

self.layer.borderColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), [1.0, 0.5, 0.5, 1.0])

The values in the array are, in order of appearance: red, green, blue, and alpha. Just like UIColor:)

数组中的值按出现顺序为:红色、绿色、蓝色和 alpha。就像UIColor:)

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGColor/#//apple_ref/c/func/CGColorCreate

https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGColor/#//apple_ref/c/func/CGColorCreate

回答by Usharao

UImage *newImage = [self imageWithColor:[UIColor colorWithRed:200/255. green:228/255. blue:194/255. alpha:0.99]];

回答by Matteo Piombo

Maybe all you need is set the borderWidth, by default it is 0, so it is not visible:

也许您只需要设置borderWidth,默认情况下它是 0,所以它不可见:

self.layer.borderWidth = 1.0

Just in case you can set the cornerRadiusif you need it rounded ... might be useful ;-)

以防万一你可以设置cornerRadius如果你需要它四舍五入......可能会有用;-)

self.layer.cornerRadius = 4.0