是在万能的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了,嘎方便的。