美文网首页
对UIColor的取色封装

对UIColor的取色封装

作者: 精神薇 | 来源:发表于2018-10-12 16:40 被阅读0次
    //hex填写十六进制值
    #define COLOR_WITH_HEX(hexValue)     [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16)) / 255.0 green:((float)((hexValue & 0xFF00) >> 8)) / 255.0 blue:((float)(hexValue & 0xFF)) / 255.0 alpha:1.0f]
    //hex填写十六进制值
    +(UIColor*)colorWithRGB:(NSUInteger)hex
                      alpha:(CGFloat)alpha
    {
        float r, g, b, a;
        a = alpha;
        b = hex & 0x0000FF;
        hex = hex >> 8;
        g = hex & 0x0000FF;
        hex = hex >> 8;
        r = hex;
        
        return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a];
    }
    //hexString填写十六进制字符串
    + (UIColor *)colorWithHexString:(NSString *)hexString {
        return [UIColor colorWithHexString:hexString alpha:1.0];
    }
    //hexString填写十六进制字符串
    + (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
        if ([hexString hasPrefix:@"0x"] || [hexString hasPrefix:@"0X"]) {
            hexString = [hexString substringFromIndex:2];
        } else if ([hexString hasPrefix:@"#"]) {
            hexString = [hexString substringFromIndex:1];
        }
        
        unsigned int value = 0;
        BOOL flag = [[NSScanner scannerWithString:hexString] scanHexInt:&value];
        if(NO == flag)
            return [UIColor clearColor];
        float r, g, b, a;
        a = alpha;
        b = value & 0x0000FF;
        value = value >> 8;
        g = value & 0x0000FF;
        value = value >> 8;
        r = value;
        
        return [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a];
    }
    

    相关文章

      网友评论

          本文标题:对UIColor的取色封装

          本文链接:https://www.haomeiwen.com/subject/mwlgaftx.html