iOS颜色转换成图片的方法
Posted 独处守心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS颜色转换成图片的方法相关的知识,希望对你有一定的参考价值。
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颜色转换成图片的方法的主要内容,如果未能解决你的问题,请参考以下文章