16进制颜色(html颜色值)字符串转为UIColor

互联网 App 中经常会用到 html 颜色值转换 UIColor,比如:#FF9900、0XFF9900 等颜色字符串,以下方法可以将这些字符串转换为 UIColor 对象。

 1 #define DEFAULT_VOID_COLOR [UIColor clearColor]
 2 
 3 
 4 
 5 
 6 
 7 + (UIColor *) colorWithHexString: (NSString *) stringToConvert
 8 {
 9     NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
10     
11     // String should be 6 or 8 characters
12     if ([cString length] < 6) return DEFAULT_VOID_COLOR;
13     
14     // strip 0X if it appears
15     if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
16     if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
17     if ([cString length] != 6) return DEFAULT_VOID_COLOR;
18     // Separate into r, g, b substrings
19     NSRange range;
20     range.location = 0;
21     range.length = 2;
22     NSString *rString = [cString substringWithRange:range];
23     
24     range.location = 2;
25     NSString *gString = [cString substringWithRange:range];
26     
27     range.location = 4;
28     NSString *bString = [cString substringWithRange:range];
29     
30     // Scan values
31     unsigned int r, g, b;
32     [[NSScanner scannerWithString:rString] scanHexInt:&r];
33     [[NSScanner scannerWithString:gString] scanHexInt:&g];
34     [[NSScanner scannerWithString:bString] scanHexInt:&b];
35 
36     
37     return [UIColor colorWithRed:((float) r / 255.0f)
38                            green:((float) g / 255.0f)
39                             blue:((float) b / 255.0f)
40                            alpha:1.0f];
41 }

 

posted @ 2013-08-20 13:52  ubersexual  阅读(486)  评论(0编辑  收藏  举报