How to create a colored 1x1 UIImage on the iPhone dynamically?

后端 未结 6 2031
情书的邮戳
情书的邮戳 2020-11-28 01:53

I would like to create a 1x1 UIImage dynamically based on a UIColor.

I suspect this can quickly be done with Quartz2d, and I\'m poring over the documentation trying

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 02:19

    To me, a convenience init feels neater in Swift.

    extension UIImage {
    
        convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
    
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            UIGraphicsBeginImageContext(rect.size)
            guard let context = UIGraphicsGetCurrentContext() else {
                return nil
            }
    
            context.setFillColor(color.cgColor)
            context.fill(rect)
    
            guard let image = context.makeImage() else {
                return nil
            }
            UIGraphicsEndImageContext()
    
            self.init(cgImage: image)
        }
    
    }
    

提交回复
热议问题