码迷,mamicode.com
首页 > 移动开发 > 详细

iOS颜色转换成图片的方法

时间:2020-01-04 14:12:50      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:方法   color   col   rap   ddt   size   tor   load   send   

 1 //  颜色转换为背景图片
 2 - (UIImage *)imageWithColor:(UIColor *)color {
 3     CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
 4     UIGraphicsBeginImageContext(rect.size);
 5     CGContextRef context = UIGraphicsGetCurrentContext();
 6     
 7     CGContextSetFillColorWithColor(context, [color CGColor]);
 8     CGContextFillRect(context, rect);
 9     
10     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
11     UIGraphicsEndImageContext();
12     
13     return image;
14 }

使用例子

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     
 4     UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(50, 200, 100, 50)];
 5     [button1 setTitle:@"button1" forState:UIControlStateNormal];
 6     button1.backgroundColor = [UIColor orangeColor];
 7     [button1 addTarget:self action:@selector(button1BackGroundHighlighted:) forControlEvents:UIControlEventTouchDown];
 8     [button1 addTarget:self action:@selector(button1BackGroundNormal:) forControlEvents:UIControlEventTouchUpInside];
 9     [self.view addSubview:button1];
10     
11     UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(170, 200, 100, 50)];
12     [button2 setTitle:@"button2" forState:UIControlStateNormal];
13     [button2 setBackgroundImage:[self imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
14     [button2 setBackgroundImage:[self imageWithColor:[UIColor grayColor]] forState:UIControlStateHighlighted];
15     [self.view addSubview:button2];
16 }

效果如下图:

技术图片

iOS颜色转换成图片的方法

标签:方法   color   col   rap   ddt   size   tor   load   send   

原文地址:https://www.cnblogs.com/wanli-leon/p/12148794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!