xcode 产生指定颜色的图片imageWithColor

  是在万能的stackOverflow上找到的答案,留下了,

原地址:http://stackoverflow.com/questions/6496441/creating-a-uiimage-from-a-uicolor-to-use-as-a-background-image-for-uibutton

 

通过颜色产生图片其实还是蛮常用的,以下先贴出大神的OC代码

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

下面贴出小弟的Swift代码:

    func imageWithColor(color: UIColor) -> UIImage{
        var rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
        UIGraphicsBeginImageContext(rect.size)
        var context = UIGraphicsGetCurrentContext()
        
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)
        
        var image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

只用将代码拷贝到类中直接调用就OK了,嘎方便的。

posted on 2014-09-16 16:41  SCaptain  阅读(1343)  评论(0编辑  收藏  举报

导航