iOS Developer

OC 十六进制色值转 RGB

2016-05-30  本文已影响82人  张小泺
把十六进制的色值转换成 RGB
+ (UIColor *)colorWithHexColor:(NSString *)hexColorString {
    if ([hexColorString hasPrefix:@"#"]) {
        hexColorString = [hexColorString substringFromIndex:1];
    }
    
    if (hexColorString.length != 6) {
        return  nil;
    }
    
    NSRange range = NSMakeRange(0, 2);
    NSString *redStr = [hexColorString substringWithRange:range];
    range.location = 2;
    NSString *greenStr = [hexColorString substringWithRange:range];
    range.location = 4;
    NSString *blueStr = [hexColorString substringWithRange:range];
    
    unsigned int red, green, blue;
    [[NSScanner scannerWithString:redStr] scanHexInt:&red];
    [[NSScanner scannerWithString:greenStr] scanHexInt:&green];
    [[NSScanner scannerWithString:blueStr] scanHexInt:&blue];
    
    return [UIColor colorWithRed:red / 255.0f  green:green / 255.0f blue:blue / 255.0f alpha:1];
}
上一篇下一篇

猜你喜欢

热点阅读