16进制和RGB颜色互转

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
NSString *hexString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",R]];
 
if (hexString.length == 1) {
 
hexString = [NSString stringWithFormat:@"0%@",hexString];
 
}
 
NSString *hexString1 = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",G]];
 
NSString *hexString2 = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",B]];
 
NSString *color = [NSString stringWithFormat:@"#%@%@%@",hexString,hexString1,hexString2];
 
调用16进制颜色 关键是把16进制转成RGB
 
// 颜色转换:iOS中十六进制的颜色(以#开头)转换为UIColor
 
[self  colorWithHexString:color];
 
- (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];
 
}
 
// 判断前缀并剪切掉
 
if ([cString hasPrefix:@"0X"])
 
cString = [cString substringFromIndex:2];
 
if ([cString hasPrefix:@"#"])
 
cString = [cString substringFromIndex:1];
 
if ([cString length] != 6)
 
return [UIColor clearColor];
 
// 从六位数值中找到RGB对应的位数并转换
 
NSRange range;
 
range.location = 0;
 
range.length = 2;
 
//R、G、B
 
NSString *rString = [cString substringWithRange:range];
 
range.location = 2;
 
NSString *gString = [cString substringWithRange:range];
 
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];
 
NSLog(@"r%u g%u b%u",r,g,b);
 
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
 
}
 
- (UIColor *)getColor:(NSString *)hexColor {
 
NSString *string = [hexColor substringFromIndex:1];//去掉#号
 
unsigned int red,green,blue;
 
NSRange range;
 
range.length = 2;
 
range.location = 0;
 
/* 调用下面的方法处理字符串 */
 
red = [self stringToInt:[string substringWithRange:range]];
 
range.location = 2;
 
green = [self stringToInt:[string substringWithRange:range]];
 
range.location = 4;
 
blue = [self stringToInt:[string substringWithRange:range]];
 
return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
 
}

Add a Comment

电子邮件地址不会被公开。 必填项已用*标注