How Do I Take a Screen Shot of a UIView?

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

提交回复
热议问题