swift

iOS taking a screenshot programatically – using Swift

On a project I am currently working on I recently had to use one screen as the background of the next screen. In order to achieve this I opted to take a screenshot of the initial screen, save it as a UIImage and then set it as the background image of the next screen.

public class func screenShotOfView(view: UIView) -> UIImage
    {
        UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 0);
        view.window!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image
}

I added the code above to a helper class that I could call from anywhere in my app allowing any screen to pass a screenshot of itself to the next screen.

You need to ensure that you are rendering the layer of the window and not just the view so that you capture navigation and tab bars in the screen shot.

 Scroll to top