Skip to content

Latest commit

 

History

History
53 lines (44 loc) · 1.65 KB

一次性解决十六进制颜色问题.md

File metadata and controls

53 lines (44 loc) · 1.65 KB

一次性解决十六进制颜色问题。

问题起因,随着开发的进程,经常需要后台来自定义颜色,然后后台返回的颜色格式又是不一致,比如常见的0x008000 #008000

解决方案,两者都能轻松应对。

+ (UIColor *)colorWithHexString:(NSString *)string {
    if ([string hasPrefix:@"#"]) { //#开头
        string = [string substringFromIndex:1];
    }
    if ([string hasPrefix:@"0x"]) { //0x开头
        string = [string substringFromIndex:2];
    }
    // Separate into r, g, b substrings
    NSRange range;
    range.length = 2;
    
    range.location = 0;
    NSString *rString = [string substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [string substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [string substringWithRange:range];
    
    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];
}

单独适配0x开头的十六进制颜色

/*!
 *  @brief  十六进制颜色->UIColor
 *
 *  @param value 十六进制数
 *  @param alpha 透明度 0~1.0f
 *
 *  @return 对应的颜色
 */
+ (UIColor *)nb_colorWithHex:(NSUInteger)value alpha:(CGFloat)alpha {
    CGFloat r = ((value & 0x00FF0000) >> 16) / 255.0f;
    CGFloat g = ((value & 0x0000FF00) >> 8) / 255.0f;
    CGFloat b = (value & 0x000000FF) / 255.0f;
    return [self colorWithRed:r green:g blue:b alpha:alpha];
}