How to take a screenshot programmatically?
-
Possible duplicate of [How to take a screenshot programmatically on iOS](https://stackoverflow.com/questions/2200736/how-to-take-a-screenshot-programmatically-on-ios) – Cœur Apr 30 '19 at 13:50
2 Answers
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();
-
I have implemented this into my code but it doesn't seem to be saving the screenshot in the camera roll. Am I missing something here? – RafeeJ Apr 14 '12 at 09:05
-
@RafeeSkull-manJenkins, to save it to CameraRoll you need to use `UIImageWriteToSavedPhotosAlbum`, check my edit. – iNoob Apr 15 '12 at 12:36
-
I think this code doesn't work with Camera or OpenGL frames, or maybe I'm missing something...? – Francisco Gutiérrez Apr 10 '13 at 21:45
-
@iNoob tried this but found it didn't contain status bar and navigation bar, only the view below navigation bar. How to do a full screen snap? – S1U Dec 25 '14 at 02:23
Have a look at this answer.It also takes care of retina display.
Actually to explain the process,
- Choose a image context size (probably the layer size for which you need screen shot)
- Render the layer which you want to take screenshot in the created context
- Obtain the image from the context and you are done!
-
I just wanted to add a bit of explanation on my own. So chose to answer it. – Vignesh Apr 13 '12 at 12:43