首页 > 其他 > 详细

通过#色值方式设置颜色

时间:2016-02-23 13:07:19      阅读:149      评论:0      收藏:0      [点我收藏+]
 1 + (UIColor *)colorWithRGB:(NSString *)rgbstr{
 2     NSString *newrgbstr = [rgbstr uppercaseString];
 3     NSInteger strlen = newrgbstr.length;
 4     UIColor *color = nil;
 5     unichar first = [newrgbstr characterAtIndex:0];
 6     if (first == #) {
 7         for (int i = 1; i < strlen; i++) {
 8             unichar u = [newrgbstr characterAtIndex:i];
 9             if (!(u >= 0 && u <= 9) && !(u >= A && u <=F)) {
10                 NSString *exName = [NSString stringWithFormat:@"使用%@类获取指定颜色错误", NSStringFromClass([self class])];
11                 NSException *e = [NSException exceptionWithName:exName reason:@"请检查颜色数值越界" userInfo:nil];
12                 @throw e;
13             }
14         }
15         if (newrgbstr.length == 4) {
16             unichar uarray[3];
17             for(int i = 0;i < 3;i++){
18                 uarray[i] = [newrgbstr characterAtIndex:(i+1)];
19             }
20             for (int i = 0;i < 3;i++) {
21                 uarray[i] = (uarray[i] > 9 ? (uarray[i]-A+10) : (uarray[i]-0)) * 17 % 256;
22             }
23             CGFloat r = uarray[0]/255.0f;
24             CGFloat g = uarray[1]/255.0f;
25             CGFloat b = uarray[2]/255.0f;
26             color = [UIColor colorWithRed:r green:g blue:b alpha:1];
27         }else if(newrgbstr.length == 7){
28             unichar uarray[6];
29             for(int i = 0;i < 6;i++){
30                 uarray[i] = [newrgbstr characterAtIndex:(i+1)];
31             }
32             for (int i = 0;i < 3;i++) {
33                 unichar l = uarray[2*i];
34                 unichar r = uarray[2*i+1];
35                 uarray[i] = ((l > 9 ? (l-A+10) : (l-0)) * 16 +
36                              (r > 9 ? (r-A+10) : (r-0))) % 256;
37             }
38             CGFloat r = uarray[0]/255.0f;
39             CGFloat g = uarray[1]/255.0f;
40             CGFloat b = uarray[2]/255.0f;
41             color = [UIColor colorWithRed:r green:g blue:b alpha:1];
42         }
43     }
44     return color;
45 }

可以通过#fff和#ffffff两种方式设置色值,和设计协调更方便

通过#色值方式设置颜色

原文:http://www.cnblogs.com/gpengf/p/5209380.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!