2018.9.19
一个简单的宏定义
宏定义可以直接将16进制的颜色值转成对应的UIColor对象;
#define UIColorFromRGBA(rgbValue, alpha) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:alpha]
HexString 转 UIColor
支持前缀 0x,# 标识,支持 带透明度的8位长度字符串 和 不带透明度的6位字符串,代码扫一眼就明白了;嗯,方便起见建议写入UIColor的分类中;
+ (UIColor *)ColorWithHexString:(NSString *)color {
return [UIColor ColorwithHexString:color Alpha:-1];
}
自定义当前转换颜色的 透明度,若Alpha的值小于0,则表明放弃自定义透明度的操作;
+ (UIColor *)ColorwithHexString:(NSString *)color Alpha:(CGFloat)alpha {
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) {
return [UIColor clearColor];
}
// strip 0X if it appears
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 8 && [cString length]!=6)
return [UIColor clearColor];
CGFloat insideAlpha = 1.0f;
if ([cString length]==8) {
NSString *aString = [cString substringWithRange:NSMakeRange(0, 2)];
unsigned int a;
[[NSScanner scannerWithString:aString] scanHexInt:&a];
insideAlpha = (float)a / 255.0f;
cString = [cString substringWithRange:NSMakeRange(2, 6)];
}
if (alpha>0) {
insideAlpha = alpha;
}
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//b
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:insideAlpha];
}
UIColor 转 HexString
转换完毕的字符串不含任何前缀,如有需要,请自行拼接0x,# 等惯用前缀;另,HasAlpha参数决定是否将传入UIColor的透明度也计算入结果字符串,同样的,扫一眼代码就明白了;嗯,方便起见建议写入UIColor的分类中;
+ (NSString *)HexStringWithColor:(UIColor *)color HasAlpha:(BOOL)hasAlpha {
CGFloat r, g, b, a;
[color getRed:&r green:&g blue:&b alpha:&a];
int rgb = (int)(r * 255.0f)<<16 | (int)(g * 255.0f)<<8 | (int)(b * 255.0f)<<0;
if (hasAlpha) {
rgb = (int)(a * 255.0f)<<24 | (int)(r * 255.0f)<<16 | (int)(g * 255.0f)<<8 | (int)(b * 255.0f)<<0;
}
return [NSString stringWithFormat:@"%06x", rgb];
}
最后来个简单示例
- (void)viewDidLoad {
[super viewDidLoad];
UIView *sampleView = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:sampleView];
//sampleView.backgroundColor = UIColorFromRGBA(0x00a47b, 1.0f);
sampleView.backgroundColor = [UIColor ColorWithHexString:@"0x6700a47b"];
NSString *sampleStr = [UIColor HexStringWithColor:sampleView.backgroundColor HasAlpha:YES ];
NSLog(@"%@", sampleStr);
}