-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUIColor+BTColorExtensions.m
78 lines (62 loc) · 1.89 KB
/
UIColor+BTColorExtensions.m
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// UIColor+BTColorExtensions.m
// BTToolkit
//
// Created by Thaddeus on 2/1/14.
// Copyright (c) 2014 Bluetoo. All rights reserved.
//
#import "UIColor+BTColorExtensions.h"
@implementation UIColor (BTColorExtensions)
+ (UIColor *)bt_colorWithHexString:(NSString *)hexColor
{
hexColor = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// strip # if it appears
if ([hexColor hasPrefix:@"#"])
hexColor = [hexColor substringFromIndex:1];
// string should be 6 or 8 characters RRGGBB[AA]
if (hexColor.length != 6 && hexColor.length != 8)
{
return nil;
}
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
NSString *red = [hexColor substringWithRange:range];
range.location = 2;
NSString *green = [hexColor substringWithRange:range];
range.location = 4;
NSString *blue = [hexColor substringWithRange:range];
range.location = 6;
NSString *alpha = @"FF";
if(hexColor.length == 8)
{
alpha = [hexColor substringWithRange:range];
}
// Scan values
unsigned int r, g, b, a;
[[NSScanner scannerWithString:red] scanHexInt:&r];
[[NSScanner scannerWithString:green] scanHexInt:&g];
[[NSScanner scannerWithString:blue] scanHexInt:&b];
[[NSScanner scannerWithString:alpha] scanHexInt:&a];
return [UIColor colorWithRed:(float)r/255.0f green:(float)g/255.0f blue:(float)b/255.0f alpha:(float)a/255.f];
}
- (CGFloat)bt_redComponent
{
CGFloat r = 0.0f;
[self getRed:&r green:nil blue:nil alpha:nil];
return r;
}
- (CGFloat)bt_greenComponent
{
CGFloat g = 0.0f;
[self getRed:nil green:&g blue:nil alpha:nil];
return g;
}
- (CGFloat)bt_blueComponent
{
CGFloat b = 0.0f;
[self getRed:nil green:nil blue:&b alpha:nil];
return b;
}
@end