How can I obtain a CGColor from RGB values?
44,382
Solution 1
You have to give the values between 0 and 1.0. So divide the RGB values by 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
Solution 2
You can get that down to one line in Swift 3:
avLayer.backgroundColor = UIColor.red.CGColor
Solution 3
On Mac OS X there is CGColorCreateGenericRGB()
, but it doesn't exist on iOS. You can use CGColorCreate
with appropriate parameters, though.
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
:)
Solution 4
UImage *newImage = [self imageWithColor:[UIColor colorWithRed:200/255. green:228/255. blue:194/255. alpha:0.99]];
Author by
alionthego
Updated on December 29, 2020Comments
-
alionthego over 3 years
I am trying to create a custom RGB
CGColor
using Swift to use as a border color for aUIButton
. I've tried following code but the color is not visible: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
CGColor
directly from RGB values? -
Matteo Piombo about 9 years@Shruti is correct about the
CGFloat
values you should pass to UICcolor(...) -
alionthego about 9 yearshi. thanks for your reply. i had already set the borderWidth. The answer above dividing the values by 255 was the solution i was looking for. thx.
-
alionthego about 9 yearsthanks very much. i actually found that method in the documentation but was working with iOS. I was wondering why I was not able to use it but now you made it clear that it is just available for os x. thanks.