user15192869
user15192869

Reputation:

Swift generate single UIImage out of two UIImages side by side

I found an answer for this same question for Objective-C @ Saving two UIImages side-by-side as one combined image? but not for Swift.

I want to combine two UIImages side-by-side to create one UIImage. Both images would be merged at the border and maintain original resolution(no screen-shots).

How can I save the two images as one image?

ImageA + ImageB = ImageC

enter image description here

Upvotes: 3

Views: 1561

Answers (1)

David Pasztor
David Pasztor

Reputation: 54716

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 UIImages):

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)
        }
    }
}

merged result

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

Upvotes: 5

Related Questions