去網上找了下,主要是這種方法:
CGFloat R, G, B;
UIColor *uiColor = [lblDate textColor];
CGColorRef color = [uiColor CGColor];
int numComponents = CGColorGetNumberOfComponents(color);
if (numComponents == 4)
{
const CGFloat *components = CGColorGetComponents(color);
R = components[0];
G = components[1];
B = components[2];
}
但是這個方法有個問題,就是對非rgb分量的無法擷取到,比如[UIColor blackColor]就無法擷取到。
果然程式設計方面的東西國外回答的好,位址:http://stackoverflow.com/questions/4700168/get-rgb-value-from-uicolor-presets
- (void)getRGBComponents:(CGFloat [3])components forColor:(UIColor *)color {
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char resultingPixel[4];
CGContextRef context = CGBitmapContextCreate(&resultingPixel,
1,
1,
8,
4,
rgbColorSpace,
kCGImageAlphaNoneSkipLast);
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, CGRectMake(0, 0, 1, 1));
CGContextRelease(context);
CGColorSpaceRelease(rgbColorSpace);
for (int component = 0; component < 3; component++) {
components[component] = resultingPixel[component] / 255.0f;
}
}
上面這個方法即可,使用如下:
CGFloat components[3];
[self getRGBComponents:components forColor:[UIColor grayColor]];
NSLog(@"%f %f %f", components[0], components[1], components[2]);
親測了一下,完全沒有問題,擷取都是正确的。