swift3uiimagescalephotolibrary

Save newly scaled image to PhotoLibrary


I would like the user to be able to scale an image using UIPinchGesture. When the image is scaled to the size they would like, I want the ability to save that newly scaled and background UIView as a high resolution .png to the PhotoLibrary.

Here is my scale image code and my save code:

//touch scale image action

@IBAction func scaleImage(_ sender: UIPinchGestureRecognizer) {

    myImageView.transform = CGAffineTransform(scaleX: sender.scale, y: sender.scale)
}

//save image function

@IBAction func saveArtwork(_ sender: AnyObject) {


    UIGraphicsBeginImageContext(self.myImageView.bounds.size)

    // The code below may solve your problem
    myImageView.layer.render(in: UIGraphicsGetCurrentContext()!)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    let activity = UIActivityViewController(activityItems: [image!], applicationActivities: nil)
    present(activity, animated: true, completion: nil)



}

I am making an app where you can scale an image and save the new scale, it can be as large or as small as you would like if it goes out of bounds i want it to crop what is out of view. if it is a scaled small, i would like the background to be saved so you can see the tiny image against the editing backdrop. the original image is an instagram square photo. this is the app where i scale the image to be very small. i would like it to appear just this way with the black background as a new photo that is the same resolution and aspect ratio as the screen. so it will appear to be a black portrait rectangle with the new scaled image.my app saves this image to the library it is low resolution, unscaled and the background it looks to be transparent and appears white. not what i want.

The result I am getting now is that the image appears to scale, then when I save it is centered and cropped to image view bounds on the left and right.


Solution

  • AHA! I got it, I created another Subview, and made my imageView a child of that view and then gave that newly created view an outlet and changed the code to this:

    @IBAction func saveArtwork(_ sender: AnyObject) {

        UIGraphicsBeginImageContext(self.captureView.bounds.size)
    
        // The code below may solve your problem
        captureView.layer.render(in: UIGraphicsGetCurrentContext()!)
    
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        let activity = UIActivityViewController(activityItems: [image!], applicationActivities: nil)
        present(activity, animated: true, completion: nil)
    }
    

    new view is captureView.

    Now it works but it looks like crap. It's very low res. I have to figure out how to take this snapshot and have it be the resolution of the device.