Swift 从两个并排的 UIImage 中生成单个 UIImage

Swift generate single UIImage out of two UIImages side by side

我找到了同一个问题的答案 Objective-C@ Saving two UIImages side-by-side as one combined image? 但不适用于 Swift.

我想并排组合两个 UIImage 来创建一个 UIImage。两个图像将在边界处合并并保持原始分辨率(无屏幕截图)。

如何将两张图片保存为一张图片?

图片A + 图片B = 图片C

您可以使用 linked question 中的想法,即使用 UIGraphicsContextUIImage.draw 并排绘制 2 个图像,然后创建一个新的 UIImage从上下文。

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

用法(假设leftImagerightImage都是UIImage):

let mergedImage = leftImage.mergedSideBySide(with: rightImage)

功能演示(使用 SwiftUI 以使用预览更快地显示):

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

UIColor.image 函数来自 Create UIImage with solid color in Swift.