iOS 颜色转换 (10进制<—>16进制)
2019-05-16 本文已影响0人
吃货_X
/** 根据颜色获取RGB值 */
- (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)];
}
/** RGB转十六进制 */
- (NSArray *)getColorWithRgb:(NSArray *)array{
int red,green,blue;
[[NSScanner scannerWithString:[NSString stringWithFormat:@"%@",array[0]]] scanInt:&red];
[[NSScanner scannerWithString:[NSString stringWithFormat:@"%@",array[1]]] scanInt:&green];
[[NSScanner scannerWithString:[NSString stringWithFormat:@"%@",array[2]]] scanInt:&blue];
NSMutableArray *rgbArray = @[@(red),@(green),@(blue)].mutableCopy;
for (int i = 0; i < rgbArray.count; i++) {
NSString *value = [NSString stringWithFormat:@"%02x",[rgbArray[i] intValue]];
rgbArray[i] = value;
}
return @[[rgbArray componentsJoinedByString:@""],GetColor(red, green, blue, 1)];
}
/** 16进制转RGB */
- (NSArray *)getColor:(NSString *)hexColor {
unsigned int red,green,blue;
NSRange range;
range.length = 2;
range.location = 0;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
range.location = 2;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
range.location = 4;
[[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
return @[@[@(red),@(green),@(blue)],GetColor(red, green, blue, 1)];
}
备注:以上代码部分来自网上文档