How to create a image with a color such as [UIColor redColor].
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
How to create a image with a color such as [UIColor redColor].
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CIImage* outputImage = nil;
CIFilter* blueGenerator = [CIFilter filterWithName:@"CIConstantColorGenerator"];
CIColor* blue = [CIColor colorWithString:@"0.1 0.5 0.8 1.0"];
[blueGenerator setValue:blue forKey:@"inputColor"];
CIImage* blueImage = [blueGenerator valueForKey:@"outputImage"];
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
[self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state];
}
+ (UIImage *)imageFromColor:(UIColor *)color {
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
I have solved this by creating a category of UIImage. And it is better to use the category in such scenarios.
Here is my code:
In UIImage+Customized.h
#import <UIKit/UIKit.h>
@interface UIImage (Customized)
/**
*Return the image from Color given
*/
+ (UIImage *)imageWithColor:(UIColor *)color;
@end
In UIImage+Customized.m
#import "UIImage+Customized.h"
@implementation UIImage (Customized)
+ (UIImage *)imageWithColor:(UIColor *)color
{
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
And use it like this. For example, let's assume you want to set background image of button, then use it like:
[btnDone setBackgroundImage:[UIImage imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
NB: Import the Category in the viewController where you want to use the method.