Create UIImage Programmatically in Swift 4

December 20, 2018 ยท 2 minute read

Create UIImage Programmatically Swift 4

Learning to unit test and need to work with images, here’s how to create a UIImage from scratch. Just determine what color or size you need and add this extension to your class.

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)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        guard let cgImage = image?.cgImage else { return nil }
        self.init(cgImage: cgImage)

Now you can create an image with a just a custom color:

 let redImage = UIImage(color: .red)
 **** OR ****
 Create one with a custom size and color:
 let redImage200x200 = UIImage(color: .red, size: CGSize(width: 200, height: 200)

Buy me a coffeeBuy me a coffee