How Do I Take a Screen Shot of a UIView?

后端 未结 15 2590
-上瘾入骨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)
    
    0 讨论(0)
  • 2020-11-22 09:32

    I think you may want renderInContext, not drawInContext. drawInContext is more a method you would override...

    Note that it may not work in all views, specifically a year or so ago when I tried to use this with the live camera view it did not work.

    0 讨论(0)
  • 2020-11-22 09:33
    -(UIImage *)convertViewToImage
    {
        UIGraphicsBeginImageContext(self.bounds.size);
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
      return image;
    }
    
    0 讨论(0)
  • 2020-11-22 09:34

    I have created usable extension for UIView to take screenshot in Swift:

    extension UIView{
    
    var screenshot: UIImage{
    
        UIGraphicsBeginImageContext(self.bounds.size);
        let context = UIGraphicsGetCurrentContext();
        self.layer.renderInContext(context)
        let screenShot = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return screenShot
    }
    }
    

    To use it just type:

    let screenshot = view.screenshot
    
    0 讨论(0)
  • 2020-11-22 09:34
    CGImageRef UIGetScreenImage();
    

    Apple now allows us to use it in a public application, even though it's a private API

    0 讨论(0)
  • 2020-11-22 09:35

    There is new API from iOS 10

    extension UIView {
        func makeScreenshot() -> UIImage {
            let renderer = UIGraphicsImageRenderer(bounds: self.bounds)
            return renderer.image { (context) in
                self.layer.render(in: context.cgContext)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题