您现在的位置是:首页 > 文章详情

iOS开发-16进制颜色转换

日期:2017-06-28点击:421

项目中经常会用到颜色转换,有的是通过十六进制转成数字转颜色,想简单的点直接通过字符串转一下,简单扩展了一下分类UIColor,代码如下:

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
36
37
+(UIColor *)colorWithHex:( NSString  *)hexColor{
     return  [ self  colorWithHex:hexColor alpha:1.0f];
}
//http://www.cnblogs.com/xiaofeixiang  iOS技术交流:228407086
+(UIColor *)colorWithHex:( NSString  *)hexColor alpha:( float )alpha{
     //删除空格
     NSString  *colorStr = [[hexColor stringByTrimmingCharactersInSet:[ NSCharacterSet  whitespaceAndNewlineCharacterSet]] uppercaseString];
     // String should be 6 or 8 characters
     if  ([colorStr length] < 6||[colorStr length]>7)
     {
         return  [UIColor clearColor];
     }
     //
     if  ([colorStr hasPrefix:@ "#" ])
     {
         colorStr = [colorStr substringFromIndex:1];
     }
 
     NSRange  range;
     range.location = 0;
     range.length = 2;
     //red
     NSString  *redString = [colorStr substringWithRange:range];
     //green
     range.location = 2;
     NSString  *greenString = [colorStr substringWithRange:range];
     //blue
     range.location = 4;
     NSString  *blueString= [colorStr substringWithRange:range];
     
     // Scan values
     unsigned  int  red, green, blue;
     [[ NSScanner  scannerWithString:redString] scanHexInt:&red];
     [[ NSScanner  scannerWithString:greenString] scanHexInt:&green];
     [[ NSScanner  scannerWithString:blueString] scanHexInt:&blue];
     return  [UIColor colorWithRed:(( float )red/ 255.0f) green:(( float )green/ 255.0f) blue:(( float )blue/ 255.0f) alpha:alpha];
}
本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4621523.html,如需转载请自行联系原作者
原文链接:https://yq.aliyun.com/articles/363068
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章