How Do I Take a Screen Shot of a UIView?

后端 未结 15 2599
-上瘾入骨i
-上瘾入骨i 2020-11-22 09:28

I am wondering how my iPhone app can take a screen shot of a specific UIView as a UIImage.

I tried this code but all I get is a blank image

15条回答
  •  忘了有多久
    2020-11-22 09:28

    I created this extension for save a screen shot from UIView

    extension UIView {
    func saveImageFromView(path path:String) {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
        drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
    
    }}
    

    call:

    let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
    let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
    reportView.saveImageFromView(path: pathImage)
    

    If you want to create a png must change:

    UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
    

    by

    UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
    

提交回复
热议问题