在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))


最新文章

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

热门文章

  1. watch 和 计算属性
  2. 一文带你学会国产加密算法SM4的vue实现方案
  3. MYSQL8 常用操作
  4. Java openrasp学习记录(一)
  5. 8.1Go并发
  6. NPOI导入excel为datatable (xls xlsx xlsm)
  7. React Native 架构演进
  8. SpringBoot之整合MongoDB
  9. JavaScript基础技术总结
  10. LightOJ1336