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)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
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)
*/
Or if you just want it to be a method, use the following:
func createAnImageOf(size: CGSize, color: UIColor) -> UIImage?
{
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
And as a bonus, you can rescale all your images that come in to a preset maximum width (if you want height, I’m sure you can figure it out with this snippet as a head start):
func scaleImage(image: UIImage, maximumWidth: CGFloat) -> UIImage
{
let rect: CGRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
let cgImage: CGImage = image.cgImage!.cropping(to: rect)!
return UIImage(cgImage: cgImage, scale: image.size.width / maximumWidth, orientation: image.imageOrientation)
}
Subscribe to my email list for a monthly newsletter and special updates!