Saving an image on top of another image in Swift

I would recommend reading through this thread. All your answers are there. Once you read through that article, the following code sample should help you composite the two images together properly.

func saveImage() {
    let bottomImage = UIImage(named: "bottom")!
    let topImage = UIImage(named: "top")!

    let newSize = CGSizeMake(100, 100) // set this to what you need
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)

    bottomImage.drawInRect(CGRect(origin: CGPointZero, size: newSize))
    topImage.drawInRect(CGRect(origin: CGPointZero, size: newSize))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

Hopefully this gets you going in the right direction.


Apple advises against UIGraphicsBeginImageContext, so as long as your app does not support devices older than iOS 10, then use something like this:

private func drawLogoIn(_ image: UIImage, _ logo: UIImage, position: CGPoint) -> UIImage {
    let renderer = UIGraphicsImageRenderer(size: image.size)
    return renderer.image { context in
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        logo.draw(in: CGRect(origin: position, size: logo.size))
    }
}

Besides performance gains, you get full P3 range.