Reputation: 77
I have a function which receives a UIColor
and needs to use it's RGBA values.
What I did so far was to use CGColorGetComponents
but that doesn't work well for other colorspaces (for example [UIColor blackColor]
which is in grayscale).
Using getRed green blue (in iOS 5) also doesn't work on [UIColor blackColor]
(returns false).
Any easy way of doing this?
Upvotes: 2
Views: 504
Reputation: 4406
The following method should work in most cases (except pattern-colors). Add it as a category to UIColor.
- (void)getRGBA:(CGFloat*)buffer {
CGColorRef clr = [self CGColor];
NSInteger n = CGColorGetNumberOfComponents(clr);
const CGFloat *colors = CGColorGetComponents(clr);
switch (n) {
case 2:
for(int i = 0; i<3; ++i){
buffer[i] = colors[0];
}
buffer[3] = CGColorGetAlpha(clr);
break;
case 3:
for(int i = 0; i<3; ++i){
buffer[i] = colors[i];
}
buffer[3] = 1.0;
break;
case 4:
for(int i = 0; i<4; ++i){
buffer[i] = colors[i];
}
break;
default:
break;
}
}
Upvotes: 2
Reputation: 119242
getRed:...
will return false if a color is not in the RGB color space. Pretty much the only other option is the grayscale color space, so if you try getWhite:alpha:
you should get valid values back. The RGBA equivalent of this color will then have the white value for each of the R, G and B values.
Upvotes: 0