-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUIColor+ILHexStringColor.m
More file actions
61 lines (48 loc) · 1.55 KB
/
UIColor+ILHexStringColor.m
File metadata and controls
61 lines (48 loc) · 1.55 KB
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
//
// UIColor+ILHexStringColor
// Version 1.1
// Created by Isaac Lim (isaacl.net) on 1/1/13.
//
#import "UIColor+ILHexStringColor.h"
@implementation UIColor (ILHexStringColor)
+ (UIColor *)colorWithHexString:(NSString *)str {
const char *cStr = [str cStringUsingEncoding:NSASCIIStringEncoding];
int len = strlen(cStr);
switch (len) {
case 6:
case 8:
break;
case 7:
cStr++;
len--;
break;
case 9:
cStr++;
len--;
break;
default:
NSLog(@"Please give a hex string in the form \"#ff3cbb\" or \"ff3cbb\", case-insensitive.");
return nil;
}
long x = strtol(cStr, NULL, 16);
unsigned char r = (x >> 16) & 0xFF;
unsigned char g = (x >> 8) & 0xFF;
unsigned char b = x & 0xFF;
return [UIColor colorWithRed:(float)r/255.0f
green:(float)g/255.0f
blue:(float)b/255.0f
alpha:(len == 8) ? (float)((x >> 24) & 0xFF)/255.0f : 1.0];
}
+ (NSString *)hexStringFromColor:(UIColor *)color {
int numComponents = CGColorGetNumberOfComponents(color.CGColor);
if (numComponents != 4) {
return nil;
}
const CGFloat *components = CGColorGetComponents(color.CGColor);
unsigned int r = components[0] * 255;
unsigned int g = components[1] * 255;
unsigned int b = components[2] * 255;
unsigned int a = components[3] * 255;
return [NSString stringWithFormat:@"#%2x%2x%2x%2x", a, r, g, b];
}
@end