You can use the idea from the linked question of using UIGraphicsContext
and UIImage.draw
to draw the 2 images side-by-side and then create a new UIImage
from the context.
extension UIImage {
func mergedSideBySide(with otherImage: UIImage) -> UIImage? {
let mergedWidth = self.size.width + otherImage.size.width
let mergedHeight = max(self.size.height, otherImage.size.height)
let mergedSize = CGSize(width: mergedWidth, height: mergedHeight)
UIGraphicsBeginImageContext(mergedSize)
self.draw(in: CGRect(x: 0, y: 0, width: mergedWidth, height: mergedHeight))
otherImage.draw(in: CGRect(x: self.size.width, y: 0, width: mergedWidth, height: mergedHeight))
let mergedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return mergedImage
}
}
Usage (assuming leftImage
and rightImage
are both UIImage
s):
let mergedImage = leftImage.mergedSideBySide(with: rightImage)
Demo of the function (using SwiftUI for quicker display using previews):
struct Playground_Previews: PreviewProvider {
static let leftImage = UIColor.blue.image(CGSize(width: 128, height: 128))
static let rightImage = UIColor.red.image(CGSize(width: 128, height: 128))
static let mergedImage = leftImage.mergedSideBySide(with: rightImage) ?? UIImage()
static var previews: some View {
VStack(spacing: 10) {
Image(uiImage: leftImage)
Image(uiImage: rightImage)
Image(uiImage: mergedImage)
}
}
}

The UIColor.image
function is from Create UIImage with solid color in Swift.