我想以编程方式创建一个由纯色填充的 UIImage。有人知道如何在 Swift 中执行此操作吗?
最佳答案
另一个不错的解决方案, swift 3.0
public extension UIImage {
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)
}
}
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))
关于ios - 在 Swift 中创建纯色的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26542035/