zoukankan      html  css  js  c++  java
  • convert a hexadecimal color (e.g. #FFCC88)

    The following is a simple method that will convert a hexadecimal color (e.g. #FFCC88) into an equivalent UIColor object.
    - (UIColor *) colorForHex:(NSString *)hexColor {
    hexColor = [[hexColor stringByTrimmingCharactersInSet:
    [NSCharacterSet whitespaceAndNewlineCharacterSet]
    ] uppercaseString];
    // String should be 6 or 7 characters if it includes '#'
    if ([hexColor length] < 6)
    return [UIColor blackColor];
    // strip # if it appears
    if ([hexColor hasPrefix:@"#"])
    hexColor = [cString substringFromIndex:1];
    // if the value isn't 6 characters at this point return
    // the color black
    if ([hexColor length] != 6)
    return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [hexColor substringWithRange:range];
    range.location = 2;
    NSString *gString = [hexColor substringWithRange:range];
    range.location = 4;
    NSString *bString = [hexColor substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f)
    green:((float) g / 255.0f)
    blue:((float) b / 255.0f)
    alpha:1.0f];
    }
    

    Notice that we had to first separate our the hex values for the red, green, and blue components first as substrings and then apply the NSScanner to those substrings.

  • 相关阅读:
    洛谷P2146 [NOI2015]软件包管理器
    洛谷P3038 [USACO11DEC]牧草种植Grass Planting
    洛谷P2831 愤怒的小鸟
    洛谷P1084 疫情控制
    洛谷P3258 [JLOI]2014松鼠的新家
    洛谷P1084 运输计划
    洛谷P2051 [AHOI2009]中国象棋
    洛谷P1438 无聊的数列
    洛谷P1312 Mayan游戏
    luogu P1038 神经网络
  • 原文地址:https://www.cnblogs.com/cnsoft/p/1409040.html
Copyright © 2011-2022 走看看