-3

How to create a image with a color such as [UIColor redColor].

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Andrey Oshev
  • 846
  • 7
  • 17
rui
  • 1
  • 4
  • 3
    can refer this http://stackoverflow.com/questions/1213790/how-to-get-a-color-image-in-iphone-sdk and possible duplicate – Sailendra Nov 24 '16 at 07:22

3 Answers3

1
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"];
0
- (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;
}
Andrey Oshev
  • 846
  • 7
  • 17
0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Janmenjaya
  • 4,149
  • 1
  • 23
  • 43