Saving an image on top of another image in Swift

I am learning Swift and I am creating an application that uses a personal photo and places another on top of it. Now I have a hacker solution to create a screenshot of the area and save it. I need to do this in Swift

@IBAction func saveImage(sender: AnyObject) { //Create the UIImage UIGraphicsBeginImageContext(imageView.frame.size) view.layer.renderInContext(UIGraphicsGetCurrentContext()) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //Save it to the camera roll UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } 

But it worked and no longer works. But this is also not the best solution.

So guys, how can I save an image in a camera frame from a personal image with the image as an overlay?

Help will be greatly appreciated! Thanks!

+8
source share
3 answers

I would recommend reading this thread. All your answers are there. After you read this article, the following code sample will help you assemble the two images correctly.

 func saveImage() { let bottomImage = UIImage(named: "bottom")! let topImage = UIImage(named: "top")! let newSize = CGSizeMake(100, 100) // set this to what you need UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) bottomImage.drawInRect(CGRect(origin: CGPointZero, size: newSize)) topImage.drawInRect(CGRect(origin: CGPointZero, size: newSize)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } 

Hope this helps you move in the right direction.

+20
source

Updated to Swift 3.0:

 func saveImage() { let bottomImage = UIImage(named: "bottom")! let topImage = UIImage(named: "top")! let newSize = CGSizeMake(100, 100) // set this to what you need UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) bottomImage.draw(in: CGRect(origin: CGPointZero, size: newSize))//As drawInRect is deprecated topImage.draw(at: CGRect(origin: CGPointZero, size: newSize))//As drawInRect is deprecated let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } 
+3
source

UPDATE FOR SWIFT 4

 func saveImage() { let bottomImage = UIImage(named: "your bottom image name")! let topImage = UIImage(named: "your top image name")! let newSize = CGSize(width: 100, height: 100) // set this to what you need UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) bottomImage.draw(in: CGRect(origin: CGPoint.zero, size: newSize)) topImage.draw(in: CGRect(origin: CGPoint.zero, size: newSize)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } 

To use an image, just refer to newImage

EXAMPLE HOW TO USE THE IMAGE:

  @IBOutlet weak var imageButton: UIButton! imageButton.setBackgroundImage(newImage), for: .normal) 

This is a cnoon answer edit but optimized for Swift 4.

+1
source

Source: https://habr.com/ru/post/983822/


All Articles