2016-11-24 56 views
-3

如何使用[UIColor redColor]等顏色創建圖像。使用顏色創建圖像,如ios中的[UIColor redColor]

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

可以參考這個http://stackoverflow.com/questions/1213790/how-to-get-a-color-image-in-iphone-sdk和可能重複 –

回答

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

我已經通過創建的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中導入類別。

希望它有幫助。

快樂編碼...

相關問題