ios客户端学习-颜色将16位值转换成rgb值,UIColor与字符串互转


#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue &0xFF00) >>8))/255.0 blue:((float)(rgbValue &0xFF))/255.0 alpha:1.0]


用法:

self.btnWork.backgroundColor =UIColorFromRGB(0x1874de);


其他链接:https://github.com/zhangxigithub/ZXMacro/blob/master/ZXMacro.h


2。将16进制字符串转换成uicolor

注:参数值不带#号

// 16进制字符串转换成uicolor

+(UIColor*)toUIColorByStr:(NSString*)colorStr{

    

    NSString *cString = [[colorStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];

    if ([cString length] != 6) return [UIColor blackColor];

    

    // Separate into r, g, b substrings

    NSRange range;

    range.location = 0;

    range.length = 2;

    NSString *rString = [cString substringWithRange:range];

    range.location = 2;

    NSString *gString = [cString substringWithRange:range];

    range.location = 4;

    NSString *bString = [cString 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];

}



3.将UIColor转换成16进制字符串

// 注意转换出来的字符串不带#号

+(NSString*)toStrByUIColor:(UIColor*)color{

    CGFloat r, g, b, a;

    [color getRed:&r green:&g blue:&b alpha:&a];

    int rgb = (int) (r * 255.0f)<<16 | (int) (g * 255.0f)<<8 | (int) (b * 255.0f)<<0;

    return [NSString stringWithFormat:@"%06x", rgb];

}



你可能感兴趣的:(iOS初学习)