zoukankan      html  css  js  c++  java
  • iOS 十六进制字符串 "#FFFF00" 转换成颜色对象

     1 + (UIColor *)colorWithHexStr:(NSString *)hexString {
     2     NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""] uppercaseString];
     3     CGFloat alpha, red, blue, green;
     4     switch ([colorString length]) {
     5         case 3: // #RGB
     6             alpha = 1.0f;
     7             red   = [self colorComponentFrom: colorString start: 0 length: 1];
     8             green = [self colorComponentFrom: colorString start: 1 length: 1];
     9             blue  = [self colorComponentFrom: colorString start: 2 length: 1];
    10             break;
    11         case 4: // #ARGB
    12             alpha = [self colorComponentFrom: colorString start: 0 length: 1];
    13             red   = [self colorComponentFrom: colorString start: 1 length: 1];
    14             green = [self colorComponentFrom: colorString start: 2 length: 1];
    15             blue  = [self colorComponentFrom: colorString start: 3 length: 1];
    16             break;
    17         case 6: // #RRGGBB
    18             alpha = 1.0f;
    19             red   = [self colorComponentFrom: colorString start: 0 length: 2];
    20             green = [self colorComponentFrom: colorString start: 2 length: 2];
    21             blue  = [self colorComponentFrom: colorString start: 4 length: 2];
    22             break;
    23         case 8: // #AARRGGBB
    24             alpha = [self colorComponentFrom: colorString start: 0 length: 2];
    25             red   = [self colorComponentFrom: colorString start: 2 length: 2];
    26             green = [self colorComponentFrom: colorString start: 4 length: 2];
    27             blue  = [self colorComponentFrom: colorString start: 6 length: 2];
    28             break;
    29         default:
    30             return nil;
    31             break;
    32     }
    33     return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    34 }
    35 
    36 + (CGFloat)colorComponentFrom:(NSString *)string start:(NSUInteger)start length:(NSUInteger)length {
    37     NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    38     NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    39     unsigned hexComponent;
    40     [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    41     return hexComponent / 255.0;
    42 }
  • 相关阅读:
    二叉平衡树
    红黑树
    [leetcode] LCP 比赛
    二叉搜索树
    面向对象的二叉树的实现
    二叉树的序列化与反序列化
    [leetcode] 基本计算器
    【pandas】玩转一行拆多行,多行并一行(分分合合你说了算)
    【VBA】数据溢出与解决
    【VBA】criterial 未找到命名参数
  • 原文地址:https://www.cnblogs.com/lz465350/p/9964601.html
Copyright © 2011-2022 走看看