如何在 Swift 中将多个重叠的 UIImage 组合成一个 UIImage



我正在创建一个应用程序,用户可以在其中从一组图像(多个)中进行选择,并将所选图像添加到选定的背景中。然后他们应该能够保存图像,所以我需要帮助将所有图像合并为一个要保存的图像。

ViewController 有一个大的 UIImageView 作为背景。当用户选择要添加的图像时,该图像将作为子视图添加到 UIImageView 中。

//chosenImage is a UIImageView with an chosen image
backgroundImageView.addSubView(chosenImage)

我需要将图像保存为带有叠加图像的背景视图的大小。

我怎样才能做到这一点?

我四处搜索,但只找到了 Obj-C 答案和一些不起作用的答案。

对于那些寻找相同答案的人,这就是您在按下按钮时保存图像的方法:

@IBAction func saveImage(sender: AnyObject) {
    let snapShot:UIView = backgroundImage.snapshotViewAfterScreenUpdates(true)
    UIGraphicsBeginImageContext(backgroundImage.bounds.size)
    snapShot.drawViewHierarchyInRect(backgroundImage.bounds, afterScreenUpdates: true)
    let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

}

我需要将图像保存为带有叠加图像的背景视图的大小。

您有两个选择。一种是在代码中绘制复合图像,只需将图像视图及其子视图定位的图像绘制到图像图形上下文中。但是,在您的情况下,更简单的方法是简单地呈现快照图像视图:这将实际上是图像视图及其子视图的屏幕截图,这正是用户所看到的。

最新更新