How Do I Take a Screen Shot of a UIView?

后端 未结 15 2764
-上瘾入骨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:47

    iOS 7 has a new method that allows you to draw a view hierarchy into the current graphics context. This can be used to get an UIImage very fast.

    I implemented a category method on UIView to get the view as an UIImage:

    - (UIImage *)pb_takeSnapshot {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
    
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    
        // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    

    It is considerably faster then the existing renderInContext: method.

    Reference: https://developer.apple.com/library/content/qa/qa1817/_index.html

    UPDATE FOR SWIFT: An extension that does the same:

    extension UIView {
    
        func pb_takeSnapshot() -> UIImage {
            UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
    
            drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
    
            // old style: layer.renderInContext(UIGraphicsGetCurrentContext())
    
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }
    

    UPDATE FOR SWIFT 3

        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
    
        drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    

提交回复
热议问题