使用颜色创建图像,如ios中的[UIColor redColor]

问题描述:

如何使用[UIColor redColor]等颜色创建图像。使用颜色创建图像,如ios中的[UIColor redColor]

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
+3

可以参考这个http://stackoverflow.com/questions/1213790/how-to-get-a-color-image-in-iphone-sdk和可能重复 –

- (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; 
} 

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"]; 

我已经通过创建的UIImage 的类别来解决这一点,它是更好地使用该类别中这样的场景。

这里是我的代码:

在的UIImage + Customized.h

#import <UIKit/UIKit.h> 

@interface UIImage (Customized) 

/** 
*Return the image from Color given 
*/ 
+ (UIImage *)imageWithColor:(UIColor *)color; 
@end 

在的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; 
} 

,并使用它像这样 对于例如,让我们假设你想要设置按钮的地面图像,然后使用它

USE: [btnDone了setBackgroundImage:[UIImage的imageWithColor:的UIColor redColor] forState:UIControlStateNormal];

注意:在要使用该方法的viewController中导入类别。

希望它有帮助。

快乐编码...