Search code examples
swiftswiftuiuikit

Combining images SwiftUI


I found an answer on combining two images to create one new image that can be shared and saved on this response: Stack response on how to combine two images swiftui (swift 5 answer by Glen). I am confused on how to use this in code as I am not familiar with the SwiftUI/UIKit crossover. Can you show an example of how to use this extension of UIImage to combine two images?

extension UIImage {
  func mergeWith(topImage: UIImage) -> UIImage {
    let bottomImage = self

    UIGraphicsBeginImageContext(size)

    let areaSize = CGRect(x: 0, y: 0, width: bottomImage.size.width, height:    bottomImage.size.height)
    bottomImage.draw(in: areaSize)

    topImage.draw(in: areaSize, blendMode: .normal, alpha: 1.0)

    let mergedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return mergedImage
  }
}


Solution

  • Quoting Swift docs here.

    Extensions add new functionality to an existing class, structure, enumeration, or protocol type.

    You would use the extension as below,

    let image1 = UIImage(named: "yourimage1")
    let image2 = UIImage(named: "yourimage2")
    let finalImage = image1.mergeWith(image2)
    //Use finalImage for sharing or saving..