Search code examples
iosswift3screenshot

Partial Screenshot with Swift 3


I would like to make partial screenshot in my project. However, I tried the output screenshot is not good that I want to be.
Here is my code.

let size = CGSize(width: 398, height: 300)

    UIGraphicsBeginImageContextWithOptions(size, false, 0);

    view.layer.render(in: UIGraphicsGetCurrentContext()!)

    var sourceImage = UIGraphicsGetImageFromCurrentImageContext()

    sourceImage?.draw(at: CGPoint(x: 0, y: 0))

    var cropimage = UIGraphicsGetImageFromCurrentImageContext()


    UIGraphicsEndImageContext()
    UIImageWriteToSavedPhotosAlbum(cropimage!,nil,nil,nil)

enter image description here


I would like to save only white View. If I set width and height, the output image is small and does not get completely.
Anyone help me please?


Solution

  • extend UIView and capture an image of that white view

    // Untested
    import UIKit
    
    extension UIView {
    
      func capture() -> UIImage {
    
        UIGraphicsBeginImageContextWithOptions(self.frame.size, self.opaque, UIScreen.mainScreen().scale)
        self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        return image
      }
    
    }
    

    usage:

    let whiteImage = myWhiteView.capture()