How do I get red green blue (RGB) and alpha back from a UIColor object?
This solution works for non-RGB colours as well e.g. black or white color.
UIColor *color = [UIColor blackColor];
CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;
// iOS 5
if ([color respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
[color getRed:&red green:&green blue:&blue alpha:&alpha];
} else {
// < iOS 5
const CGFloat *components = CGColorGetComponents(color.CGColor);
red = components[0];
green = components[1];
blue = components[2];
alpha = components[3];
}
// This is a non-RGB color
if(CGColorGetNumberOfComponents(color.CGColor) == 2) {
CGFloat hue;
CGFloat saturation;
CGFloat brightness;
[color getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
}
The reason for the crash when accessing SelectedColor.CGColor
could be that you do not retain the result from getColor
, perhaps what you need is:
SelectedColor = [[(ColorPickerView *)alertView getColor] retain];
You can only get the RGB color component from a UIColor
that is using the RGB color space, since you are using colorWithRed:green:blue:alpha:
that is not a problem, but be vary of this if your code changes.
With this is mind getting the color components is really easy:
const CGFloat* components = CGColorGetComponents(SelectedColor.CGColor);
NSLog(@"Red: %f", components[0]);
NSLog(@"Green: %f", components[1]);
NSLog(@"Blue: %f", components[2]);
NSLog(@"Alpha: %f", CGColorGetAlpha(SelectedColor.CGColor));