How to take a screenshot using code on iOS?
ios, screenshot, uiimage
Solution
You can use `UIGraphicsBeginImageContext` for this purpose.
For example :
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData*theImageData = UIImageJPEGRepresentation(theImage, 1.0 ); //you can use PNG too
[theImageData writeToFile:@"example.jpeg" atomically:YES];
Here
1. First i take the image context, i've given it as `myView` which is a webview, you can give whatever you wish for. This takes the image of webview that can be seen on the screen.
2 Using `UIGraphicsGetImageFromCurrentImageContext()` i convert the screenshot of my webview into an image.
3. By using `UIGraphicsEndImageContext()` i ask it end the context.
4. I'm saving the image into an `NSData` because i had to mail the screenshot. And keep it in `NSData` seemed a good option if it is used to send or save.
EDIT: To add it to the camera roll you need to write:
`UIImageWriteToSavedPhotosAlbum(theImage,nil,NULL,NULL);` after `UIGraphicsEndImageContext();`
Problem
How to take a screenshot programmatically?