前言
平常用的颜色宏大概如下
1
| #define RGBHex(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
|
考虑到蓝湖中获得的十六进制颜色值为#FF0000
,cv时需要先删除#再添加0x
,想省略这部分
实现
C
语言宏中’#’称之为字符串化操作符(Stringizing Operator),它将函数宏的实际参数转换为对应的字符串常量。利用这个特点定义如下的颜色宏
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #define HEXA(COLOR,A) ({ \ char *color = #COLOR;\ NSString *colorString = [NSString stringWithUTF8String:color]; \ colorString = [colorString stringByReplacingOccurrencesOfString:@"#" withString:@""]; \ colorString = [colorString stringByReplacingOccurrencesOfString:@"0x" withString:@""]; \ unsigned int red,green,blue; \ NSRange range; \ range.length = 2; \ range.location = 0; \ [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&red]; \ range.location = 2; \ [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&green]; \ range.location = 4; \ [[NSScanner scannerWithString:[colorString substringWithRange:range]] scanHexInt:&blue]; \ [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:A]; \ })
#define HEX(COLOR) HEXA(COLOR,1.0)
|
支持0xFF0000/#FF0000/FF0000
这三种格式