
在封裝我的小框架( ZPSegmentBarOC )的時候需要根據(jù)顏色來獲取對應(yīng)的RGB值,從而達(dá)到顏色有漸變的效果,我從網(wǎng)上找了很多資料,在這里記錄下:
方法一
/**
獲取顏色的RGB值
@param components RGB數(shù)組
@param color 顏色
*/
- (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 blackColor]];
NSLog(@"%f %f %f", components[0], components[1], components[2]);
即可獲取RGB的值;
參考: stackoverflow
方法二
- (NSArray *)getRGBWithColor:(UIColor *)color
{
CGFloat red = 0.0;
CGFloat green = 0.0;
CGFloat blue = 0.0;
CGFloat alpha = 0.0;
[color getRed:&red green:&green blue:&blue alpha:&alpha];
return @[@(red), @(green), @(blue), @(alpha)];
}
在使用的時候我們只需要將對應(yīng)的顏色傳入進(jìn)去即可,該方法就會給我們返回一個數(shù)組,里面包括了RGB還有Alpha,較方法一更為簡便;