2

I have been stuck on a situation where I want my code to take a screenshot of the screen but only the middle of it.

    @IBAction func savePhoto(_ sender: UIButton) {

    // Does not go into program
    let size = CGSize(width: view.frame.size.width, height: view.frame.size.height)

    UIGraphicsBeginImageContextWithOptions(CGSize(width:1024.0,height: 1024.0), false, UIScreen.main.scale)


    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    UIImageWriteToSavedPhotosAlbum(newImage!, nil, nil, nil)

    }

I did try making it to when it screenshots it makes it 1024x1024 and I thought that would work, but it does not.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 3
    It's probably easiest to take the full screenshot, and then crop just to part you want. Cropping in Swift can be done relatively easily: https://stackoverflow.com/a/39282670/3708242 – wottle Apr 16 '18 at 20:04

1 Answers1

0

Try this, It's Working for me. Hope, It's Helpful.

@IBAction func savePhoto(_ sender: UIButton) {

            UIGraphicsBeginImageContextWithOptions(CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height - 100), false, 0.0)
            self.view.drawHierarchy(in: CGRect(x: 0, y: 0, width: 1024.0, height: 1024.0), afterScreenUpdates: true)
            if let image = UIGraphicsGetImageFromCurrentImageContext() {
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

            }
            UIGraphicsEndImageContext();

        }
Divya Thakkar
  • 212
  • 3
  • 13
  • Thanks it really did help! mind explaining the self.view.drawHierarchy? Would really love to understand that line of code more !(: – curiousnoob Apr 18 '18 at 06:43
  • draw the view in this context in such a way that, the visible part of the screenshot starts . @vserrato129 – Divya Thakkar Apr 18 '18 at 06:52