How to take a screenshot using code on iOS?

前端 未结 2 1230
北恋
北恋 2021-02-03 16:23

How to take a screenshot programmatically?

相关标签:
2条回答
  • 2021-02-03 16:38

    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();

    0 讨论(0)
  • 2021-02-03 17:00

    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!
    0 讨论(0)
提交回复
热议问题