在开发中,我们有时候需要根据相应的颜色,得到对应的RGB值,我查找了很多,也看了对应的API,没有找到相关的,这是在网上找到了一段代码,经过修改,贴出来给有需要的伙伴儿进行参考,如果你们有好的方法,希望可以科普一下我!
废话不多说,代码如下:
- (NSMutableArray *)changeUIColorToRGB:(UIColor *)color
{
NSMutableArray *RGBStrValueArr = [[NSMutableArray alloc] init];
NSString *RGBStr = nil;
//获得RGB值描述
NSString *RGBValue = [NSString stringWithFormat:@"%@", color];
//将RGB值描述分隔成字符串
NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
//获取红色值
float r = [RGBArr[1] floatValue];
RGBStr = [NSString stringWithFormat:@"%.2lf", r];
[RGBStrValueArr addObject:RGBStr];
//获取绿色值
float g = [RGBArr[2] floatValue];
RGBStr = [NSString stringWithFormat:@"%.2lf", g];
[RGBStrValueArr addObject:RGBStr];
//获取蓝色值
float b = [RGBArr[3] floatValue];
RGBStr = [NSString stringWithFormat:@"%.2lf", b];
[RGBStrValueArr addObject:RGBStr];
float a = [RGBArr[4] floatValue];
RGBStr = [NSString stringWithFormat:@"%.2lf", a];
[RGBStrValueArr addObject:RGBStr];
//返回保存RGB值的数组
return RGBStrValueArr;
}
经过一番的查找,又找到了中相关的API的用法,此处也贴出来,更新一下这篇帖子,代码如下:
- (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)];
}
在调用的时候,只需要把颜色传入进去,比如说把redColor传入进去,返回的是一个数组,里面有对应的RGB值,还有alpha值!
谢谢观看,喜欢的话,点个赞哦~