iOS开发之十六进制颜色数据转化为UIColor对象

1.若从服务器返回的颜色字符串数据为

 hexColor:"09B57A"

hexColor分为三部分:09、B5、7A 分别对应三色值 R、G、B

十六进制 十进制
00 0
01 1
... ...
09 9
0A 10
0B 11
... ...
0F 15
10 16
11 17
12 18
... ...
1F 31
...  
FF 255
   
   

代码如下:

 

 1 - (UIColor *)getColor:(NSString *)hexColor
 2 {
 3     unsigned int red,green,blue;
 4     NSRange range;
 5     range.length = 2;
 6     
 7     //截取red部分
 8     range.location = 0;
 9     [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
10     
11     //截取green部分
12     range.location = 2;
13     [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
14     
15     //截取blue部分
16     range.location = 4;
17     [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
18     
19     return rgbColor(red, green, blue, 1.0);
20 }

 

posted @ 2014-06-15 14:46  轩宇峰  阅读(277)  评论(0编辑  收藏  举报