How Do I Take a Screen Shot of a UIView?

2018-12-31 09:46发布

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.

UIGraphicsBeginImageContext(CGSizeMake(320,480));
CGContextRef context = UIGraphicsGetCurrentContext();
[myUIView.layer drawInContext:context];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

myUIView has dimensions 320x480 an it has some sub-views. What is the correct way to do this?

15条回答
梦该遗忘
2楼-- · 2018-12-31 10:22

The following snippet is used to take screenshot :

UIGraphicsBeginImageContext(self.muUIView.bounds.size);

[myUIView.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Use renderInContext: method instead of drawInContext: method

renderInContext: method renders the receiver and its sublayers into current context. This method renders directly from the layer tree.

查看更多
看淡一切
3楼-- · 2018-12-31 10:23

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)
查看更多
大哥的爱人
4楼-- · 2018-12-31 10:25

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)
        }
    }
}
查看更多
登录 后发表回答