【发布时间】:2021-04-13 13:42:31
【问题描述】:
我找到了Objective-C这个问题的答案@ Saving two UIImages side-by-side as one combined image? 但不适用于 Swift。
我想将两个 UIImage 并排组合以创建一个 UIImage。两个图像将在边界处合并并保持原始分辨率(无屏幕截图)。
如何将两张图片保存为一张图片?
图像A + 图像B = 图像C
【问题讨论】:
我找到了Objective-C这个问题的答案@ Saving two UIImages side-by-side as one combined image? 但不适用于 Swift。
我想将两个 UIImage 并排组合以创建一个 UIImage。两个图像将在边界处合并并保持原始分辨率(无屏幕截图)。
如何将两张图片保存为一张图片?
图像A + 图像B = 图像C
【问题讨论】:
您可以使用 linked question 中的想法,即使用 UIGraphicsContext 和 UIImage.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
}
}
用法(假设leftImage和rightImage都是UIImages):
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。
【讨论】: