16进制颜色#e26562与UIColor互转,设置View背景颜色

16进制颜色#e26562与UIColor互转,设置View背景颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
    view.backgroundColor=[self colorWithHexString:@"e26562"];
    [self.view addSubview:view];
}
- (UIColor *) colorWithHexString: (NSString *)color
{
    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
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    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: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];
}

posted on 2014-07-30 14:14  恒山之阳  阅读(186)  评论(0编辑  收藏  举报

导航