最近处理UIColor 转 RGB数组时,发现网上给出的方式有时候会崩溃(数组越界) 多次尝试后确定颜色为白色时数组越界 方法内部断点发现 当传入的颜色为白色时 转换为数组值时 只有3个元素 传入其他颜色时 数组有5个元素
正常情况下 R G B分别对应第2 3 4个元素 而白色时数组总共才3个元素 当然会崩溃啦!
白色时 除了第一个元素不用管 最后一个颜色是透明度以外 只剩下1个元素了 所以猜测 当传入白色时 1 就代表R G B都是1 没有分开描述了 这样处理没毛病。
传入白色时颜色数组值
传入白其它颜色时颜色数组值
//将UIColor转换为RGB值
+ (NSMutableArray *) changeUIColorToRGB:(UIColor *)color
{
NSMutableArray *RGBStrValueArr = [[NSMutableArray alloc] init];
NSString *RGBStr = nil;
//获得RGB值描述
NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
//将RGB值描述分隔成字符串
NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
/**
白色 返回3个数组值 (猜测可能是R G B都为1的时候 就写了一个1代表 三个值都是1)
其他颜色返回5个数组值
*/
if (RGBArr.count < 4) {
//获取红色值
int r = [[RGBArr objectAtIndex:1] floatValue] * 255;
RGBStr = [NSString stringWithFormat:@"%d",r];
[RGBStrValueArr addObject:RGBStr];
//获取绿色值
int g = [[RGBArr objectAtIndex:1] floatValue] * 255;
RGBStr = [NSString stringWithFormat:@"%d",g];
[RGBStrValueArr addObject:RGBStr];
//获取蓝色值
int b = [[RGBArr objectAtIndex:1] floatValue] * 255;
RGBStr = [NSString stringWithFormat:@"%d",b];
[RGBStrValueArr addObject:RGBStr];
}else{
//获取红色值
int r = [[RGBArr objectAtIndex:1] floatValue] * 255;
RGBStr = [NSString stringWithFormat:@"%d",r];
[RGBStrValueArr addObject:RGBStr];
//获取绿色值
int g = [[RGBArr objectAtIndex:2] floatValue] * 255;
RGBStr = [NSString stringWithFormat:@"%d",g];
[RGBStrValueArr addObject:RGBStr];
//获取蓝色值
int b = [[RGBArr objectAtIndex:3] floatValue] * 255;
RGBStr = [NSString stringWithFormat:@"%d",b];
[RGBStrValueArr addObject:RGBStr];
}
//返回保存RGB值的数组
return RGBStrValueArr;
}
网友评论