-
Notifications
You must be signed in to change notification settings - Fork 0
/
UIColor+Nero.m
executable file
·105 lines (92 loc) · 3 KB
/
UIColor+Nero.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
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
//
// UIColor+Nero.m
// NeroCampusBulletinBoard
//
// Created by Nero on 15/8/1.
// Copyright (c) 2015年 TanJunqiang. All rights reserved.
//
#import "UIColor+Nero.h"
@implementation UIColor (Nero)
/**
* 解析十六位色号
*
* @param colorNum 色号
* @param alpha 透明度
*
* @return 原RGBa方法
*/
+ (UIColor *)colorWithSixteenColorNumber:(NSString *)colorNum alpha:(CGFloat)alpha
{
// 删除字符串中的空格
NSString *colorNumStr = [[colorNum stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// 控制色号格式
if (([colorNumStr length] < 6) || ([colorNumStr length] > 8))
{
return [UIColor clearColor];
}
// 如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾
if ([colorNumStr hasPrefix:@"0X"])
{
colorNumStr = [colorNumStr substringFromIndex:2];
}
// 如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾
if ([colorNumStr hasPrefix:@"#"])
{
colorNumStr = [colorNumStr substringFromIndex:1];
}
// 如果整好是6位色号则直接向下计算
// 解析R、G、B
NSRange range;
range.location = 0;
range.length = 2;
// R
NSString *rString = [colorNumStr substringWithRange:range];
// G
range.location = 2;
NSString *gString = [colorNumStr substringWithRange:range];
// B
range.location = 4;
NSString *bString = [colorNumStr substringWithRange:range];
// 解析十六进制
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:alpha];
}
// 若没有透明度参数,则默认alpha值为1
/**
* 解析十六位色号
*
* @param colorNum 色号
*
* @return 原RGBa方法
*/
+ (UIColor *)colorWithSixteenColorNumber:(NSString *)colorNum{
return [self colorWithSixteenColorNumber:colorNum alpha:1.0f];
}
/**
* 获得随机色(可透明)
*
* @return Class: UIColor
*/
+ (UIColor *)randomColor {
CGFloat red = (CGFloat)arc4random() / (CGFloat)ARC4RANDOM_MAX;
CGFloat blue = (CGFloat)arc4random() / (CGFloat)ARC4RANDOM_MAX;
CGFloat green = (CGFloat)arc4random() / (CGFloat)ARC4RANDOM_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}
/**
* 获得随机色(可透明)
*
* @param alpha 不透明度
*
* @return Class: UIColor
*/
+ (UIColor *)randomColorWithAlpha:(CGFloat)alpha {
CGFloat red = (CGFloat)arc4random() / (CGFloat)ARC4RANDOM_MAX;
CGFloat blue = (CGFloat)arc4random() / (CGFloat)ARC4RANDOM_MAX;
CGFloat green = (CGFloat)arc4random() / (CGFloat)ARC4RANDOM_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}
@end