Swift 从两个 UIImage 并排生成单个 UIImage
Posted
技术标签:
【中文标题】Swift 从两个 UIImage 并排生成单个 UIImage【英文标题】:Swift generate single UIImage out of two UIImages side by side 【发布时间】:2021-04-13 13:42:31 【问题描述】:我找到了Objective-C这个问题的答案@ Saving two UIImages side-by-side as one combined image? 但不适用于 Swift。
我想将两个 UIImage 并排组合以创建一个 UIImage。两个图像将在边界处合并并保持原始分辨率(无屏幕截图)。
如何将两张图片保存为一张图片?
图像A + 图像B = 图像C
【问题讨论】:
【参考方案1】:您可以使用 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
都是UIImage
s):
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。
【讨论】:
以上是关于Swift 从两个 UIImage 并排生成单个 UIImage的主要内容,如果未能解决你的问题,请参考以下文章