How can I obtain a CGColor from RGB values? How can I obtain a CGColor from RGB values? swift swift

How can I obtain a CGColor from RGB values?


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


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

avLayer.backgroundColor = UIColor.red.CGColor


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 :)

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