iOS--16进制颜色转换UIColor

2017-11-08  本文已影响0人  WorldPeace_hp

代码:

+ (UIColor *)colorWithHex:(NSString *)hex
{
    if (!hex || hex.length == 0 || ![hex isKindOfClass:[NSString class]]) {
        return nil;
    }
    
    if ([hex hasPrefix:@"#"]) {
        hex = [hex substringFromIndex:1];
    }
    NSScanner *scanner = [NSScanner scannerWithString:hex];
    unsigned hexNum;
    if (![scanner scanHexInt:&hexNum]) {
        return nil;
    }
    
    int r = (hexNum >>16) & 0xFF;
    int g = (hexNum >>8) & 0xFF;
    int b = (hexNum) & 0xFF;
    
    return [UIColor colorWithRed:r /255.0f
                           green:g /255.0f
                            blue:b /255.0f
                           alpha:1.0f];
}
上一篇下一篇

猜你喜欢

热点阅读