[英]How can I combine multiple overlapping UIImages into one UIImage in Swift?
I am creating an app where users can choose from a collection of images (multiple) and add the chosen image to a chosen background.我正在创建一个应用程序,用户可以在其中从一组图像(多个)中进行选择,并将所选图像添加到所选背景中。 They should then be able to save the image, so I need help merging all the images into one to be saved.
然后他们应该能够保存图像,因此我需要帮助将所有图像合并为一张以进行保存。
The ViewController has a large UIImageView which serves as the background. ViewController 有一个大的 UIImageView 作为背景。 When the user selects an image to add, the image is added to the UIImageView as a subview.
当用户选择要添加的图像时,该图像将作为子视图添加到 UIImageView。
//chosenImage is a UIImageView with an chosen image
backgroundImageView.addSubView(chosenImage)
I need to save the image as the size of the backgroundView with the overlaid images.我需要将图像保存为带有重叠图像的背景视图的大小。
How can I achieve this?我怎样才能做到这一点?
I have searched around but only found Obj-C answers and some that don't work.我四处搜索,但只找到了 Obj-C 的答案和一些不起作用的答案。
For those looking for the same answer this is what you do to save the image on button press:对于那些寻找相同答案的人,这就是您在按下按钮时保存图像的方法:
@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)
}
I need to save the image as the size of the backgroundView with the overlaid images.
我需要将图像保存为带有重叠图像的背景视图的大小。
You have two choices.你有两个选择。 One is to draw a composite image in code, just drawing the images, positioned as they are by the image view and its subviews, into an image graphics context.
一种是在代码中绘制合成图像,只需将图像按图像视图及其子视图的位置绘制到图像图形上下文中。 In your case, though, a simpler approach would be simply to render or snapshot the image view: that will effectively be a screen shot of the image view and its subviews, which is exactly what the user is seeing.
但是,在您的情况下,更简单的方法是简单地渲染或快照图像视图:这实际上是图像视图及其子视图的屏幕截图,这正是用户所看到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.