iOS -UIColor随机生成颜色的方法

时间:2023-03-08 20:17:16
iOS -UIColor随机生成颜色的方法

在iOS 中的UIColor拥有这么多关于颜色的类方法,对于一般常见的UI控件,我们可以通过[UIColorblackColor]设置背景色

eg:设置button 的背景色为红色

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[button setBackgroundColor:[UIColor redColor]];
// Some convenience methods to create colors.  These colors will be as calibrated as possible.
// These colors are cached.
+ (UIColor *)blackColor; // 0.0 white
+ (UIColor *)darkGrayColor; // 0.333 white
+ (UIColor *)lightGrayColor; // 0.667 white
+ (UIColor *)whiteColor; // 1.0 white
+ (UIColor *)grayColor; // 0.5 white
+ (UIColor *)redColor; // 1.0, 0.0, 0.0 RGB
+ (UIColor *)greenColor; // 0.0, 1.0, 0.0 RGB
+ (UIColor *)blueColor; // 0.0, 0.0, 1.0 RGB
+ (UIColor *)cyanColor; // 0.0, 1.0, 1.0 RGB
+ (UIColor *)yellowColor; // 1.0, 1.0, 0.0 RGB
+ (UIColor *)magentaColor; // 1.0, 0.0, 1.0 RGB
+ (UIColor *)orangeColor; // 1.0, 0.5, 0.0 RGB
+ (UIColor *)purpleColor; // 0.5, 0.0, 0.5 RGB
+ (UIColor *)brownColor; // 0.6, 0.4, 0.2 RGB
+ (UIColor *)clearColor; // 0.0 white, 0.0 alpha

如果需要更多颜色怎么解决呢?

Apple公司为我们提供了另外一个方法:

+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;

从方法名可以看出

使用该方法设置我们需要的颜色需要三个(CGFloat)参数:(CGFloat)red
(CGFloat)green (CGFloat)blue
和一个(CGFloat)设置透明度。

我们常说的RGB三基色:范围0-255;而这三个参数确实需要归一化后的参数,即范围为0-1;

所以我们在使用的过程中,需要先对RGB归一化为:R/255.0 G/255.0 B/255.0;

eg:我们随机生成RGB,后设置颜色。

    int R = (arc4random() % 256) ;
int G = (arc4random() % 256) ;
int B = (arc4random() % 256) ;
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[button setBackgroundColor:[UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1]];

在此基础上我们可以写出随机色产生的宏:

#define random(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)/255.0]

#define randomColor random(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256))