颜色相关

颜色:3种颜色通道 R G B

  • 颜色表达方式: 24位,32位
    • 每一个颜色通道是8位,0~256
      R:213 G:213 B:213

    • (#ffffff)
      R:FF => 10进制 255
      G:FF 255
      B:FF 255

    • (#:)美工16进制表示形式

    • (0x:)OC16进制表达式

自定义颜色

#define SHColor(r,g,b) [UIColor colorWithRed:(r) / 256.0 green:(g) / 256.0 blue:(b) / 256.0 alpha:1]

代码

  • 外部调用

    @property (weak, nonatomic) IBOutlet UILabel *labelView;

    _labelView.textColor = [UIColor colorWithHexString:@"eb3535"];

#import 

@interface UIColor (Hex)

// 默认alpha位1
+ (UIColor *)colorWithHexString:(NSString *)color;

//从十六进制字符串获取颜色,
//color:支持@“#123456”、 @“0X123456”、 @“123456”三种格式
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;

@end




//
//  UIColor+Hex.m
#import "UIColor+Hex.h"

@implementation UIColor (Hex)

+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
    //删除字符串中的空格
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
    {
        return [UIColor clearColor];
    }
    // strip 0X if it appears
    //如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾
    if ([cString hasPrefix:@"0X"])
    {
        cString = [cString substringFromIndex:2];
    }
    //如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾
    if ([cString hasPrefix:@"#"])
    {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6)
    {
        return [UIColor clearColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    /*
     NSScanner是一个类族,可以用scannerWithString:或localizedScannerWithString:方法初始化一个scanner,返回一个scanner对象并用你传递的字符串参数初始化其string属性,刚创建时scanner对象指向字符串的开头。scanner方法开始扫描,比如scanInt:,scanDouble:,scanString:intoString:,搜索字符串中的整型值,并赋值给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:alpha];
}

//默认alpha值为1
+ (UIColor *)colorWithHexString:(NSString *)color
{
    return [self colorWithHexString:color alpha:1.0f];
}

@end

你可能感兴趣的:(颜色相关)