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

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

Solution 4

UImage *newImage = [self imageWithColor:[UIColor colorWithRed:200/255. green:228/255. blue:194/255. alpha:0.99]];
Share:
44,382
alionthego
Author by

alionthego

Updated on December 29, 2020

Comments

  • alionthego
    alionthego over 3 years

    I am trying to create a custom RGB CGColor using Swift to use as a border color for a UIButton. 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
    Matteo Piombo about 9 years
    @Shruti is correct about the CGFloat values you should pass to UICcolor(...)
  • alionthego
    alionthego about 9 years
    hi. 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
    alionthego about 9 years
    thanks 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.