我想以编程方式创建由纯色填充的UIImage。有人知道如何在Swift中执行此操作吗?
另一个与 Swift 2.2 兼容的不错的解决方案是以这种方式在UIImage中创建另一个构造函数:
public extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.CGImage else { return nil } self.init(CGImage: cgImage) } }
这样,您可以通过以下方式创建自定义彩色图像:
let redImage = UIImage(color: .redColor())
或者,可以选择创建具有自定义尺寸的图像:
let redImage200x200 = UIImage(color: .redColor(), size: CGSize(width: 200, height: 200))
斯威夫特3.0
public extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } }