Sunday, July 10, 2016

UIImage from a UIColor

Many time graphic team are very busy and they are not able to provide single color image or background for my controller. So, I do google and found  Below code help me to convert UIColor to UIImage.

In Objective-c 

+ (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;
}
UIImage *img = [YourClassName imageFromColor:[UIColor blueColor]];

In Swift 2.0

extension UIImage {
    static func fromColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}  
let img = UIImage.fromColor(.blueColor())

For alpha replace 
UIGraphicsBeginImageContext(rect.size);
With
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);



























No comments:

Post a Comment