Reputation: 692
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. When the user selects an image to add, the image is added to the UIImageView as a subview.
//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.
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)
}
Upvotes: 3
Views: 1834
Reputation: 535169
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.
Upvotes: 2