iOS -UIColor随机生成颜色的方法
2024-09-01 10:14:28
在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))
最新文章
- [BZOJ2768][JLOI2010]冠军调查(最小割)
- 随机生成器、thread(暂停)、清屏定义
- element.style覆盖了我的样式!!
- img onerror事件
- 全景智慧城市——NOW!!!VRSHOPPING颠覆你的购物认知!
- 相似QQ对话框上下部分可拖动代码
- 《jQuery精品教程视频》-每天的复习笔记
- Tomb Raider
- Emmet.vim 教程
- RabbitMQ:Docker环境下搭建rabbitmq集群
- 【转】在xcode5中修改整个项目名
- Python基础3--Python复杂数据类型
- iOS 实时音频采集与播放Audio Unit使用
- AndroidStudio-Unable to save settings Failed to save settings. Please restart Android Studio
- .Net 两个对像之间的映射 (一 )
- Luogu 4724 三维凸包
- Bootstrap标签Tabs
- linux设置支持中文
- intellijidea课程 intellijidea神器使用技巧 3-2 livetemplate
- vuex mapGetters