How to take a screenshot programmatically on iOS

前端 未结 20 2097
一生所求
一生所求 2020-11-22 01:42

I want a screenshot of the image on the screen saved into the saved photo library.

20条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 02:07

    This will work with swift 4.2, the screenshot will be saved in library, but please don't forget to edit the info.plist @ NSPhotoLibraryAddUsageDescription :

      @IBAction func takeScreenshot(_ sender: UIButton) {
    
        //Start full Screenshot
        print("full Screenshot")
        UIGraphicsBeginImageContext(card.frame.size)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        var sourceImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageWriteToSavedPhotosAlbum(sourceImage!, nil, nil, nil)
    
        //Start partial Screenshot
        print("partial Screenshot")
        UIGraphicsBeginImageContext(card.frame.size)
        sourceImage?.draw(at: CGPoint(x:-25,y:-100)) //the screenshot starts at -25, -100
        var croppedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageWriteToSavedPhotosAlbum(croppedImage!, nil, nil, nil)
    
    }
    

提交回复
热议问题