GaoLi's Blog

从十六进制字符串中获取颜色

从十六进制字符串中获取颜色,并返回相应 UIColor 对象,参数 hexString 支持 FFFFFF #FFFFFF 0xFFFFFF 三种格式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
+ (UIColor *)colorWithHexString:(NSString *)hexString {
return [self colorWithHexString:hexString alpha:1.0f];
}
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
hexString = [hexString uppercaseString];
if ([hexString hasPrefix:@"#"]) {
hexString = [hexString substringFromIndex:1];
}
if ([hexString hasPrefix:@"0X"]) {
hexString = [hexString substringFromIndex:2];
}
if (hexString.length != 6) {
return [UIColor clearColor];
}
NSString *rString = [hexString substringWithRange:NSMakeRange(0, 2)];
NSString *gString = [hexString substringWithRange:NSMakeRange(2, 2)];
NSString *bString = [hexString substringWithRange:NSMakeRange(4, 2)];
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:alpha];
}

注意 colorWithRed:green:blue:alpha: 方法中 RGB 的取值范围在 0.0 ~ 1.0 之间,
而并非我们习惯认为的 0 ~ 255 之间,设置错误会导致某些真机上颜色不显示问题。