• 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 }
  • 相关阅读:
    GMap.NET 随谈
    Chrome Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101
    Java 自定义枚举
    如何得到全国省市经纬度范围
    Jquery formwizard 入门 【前台 向导功能】
    Eclipse Juno 安装 Aptana 3.3,支持jquery智能提示
    Ant学习【实践1】
    euerka总结 当幸福来敲门
    Spring Boot 热启动插件 当幸福来敲门
    ASP.NET 2.0 Provider Model 详细分析
  • 原文地址:https://www.cnblogs.com/ubersexual/p/3270059.html
Copyright © 2020-2023  润新知