How to get RGB values from UIColor?

Solution 1:

In iOS 5 you could use:

CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0;
[multipliedColor getRed:&red green:&green blue:&blue alpha:&alpha];

Solution 2:

const CGFloat *colors = CGColorGetComponents( curView.backgroundColor.CGColor );

These links provide further details:

  • UIColor Reference
  • CGColorGetComponents reference

Solution 3:

SWIFT 3 & 4

I found that cgColor.components would not always return 4 color values, so I changed this so it gets them from a CIColor wrapper

extension UIColor {
    var redValue: CGFloat{ return CIColor(color: self).red }
    var greenValue: CGFloat{ return CIColor(color: self).green }
    var blueValue: CGFloat{ return CIColor(color: self).blue }
    var alphaValue: CGFloat{ return CIColor(color: self).alpha }
}

SWIFT 2

extension UIColor {
    var red: CGFloat{ return CGColorGetComponents(self.CGColor)[0] }
    var green: CGFloat{ return CGColorGetComponents(self.CGColor)[1] }
    var blue: CGFloat{ return CGColorGetComponents(self.CGColor)[2] }
    var alpha: CGFloat{ return CGColorGetComponents(self.CGColor)[3] }
}

It's not the most efficient way so I wouldn't go using this where a view will be constantly re-drawn.

Solution 4:

Hopefully this will be helpful

CGFloat red, green, blue, alpha;

//Create a sample color

UIColor *redColor = [UIColor redColor];

//Call 

[redColor getRed: &red 
  green: &green
  blue: &blue 
  alpha: &alpha];
NSLog(@"red = %f. Green = %f. Blue = %f. Alpha = %f",
  red,
  green,
  blue,
  alpha);