项目开发中有时候会遇到单色图片,每次都需要UI切图,其实可以根据颜色创建图片,扩展UIImage,代码如下:
extension UIImage {
static func from(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
测试代码:
imgView.image = UIImage.from(color: .red)