How to take a screenshot programmatically on iOS

前端 未结 20 2081
一生所求
一生所求 2020-11-22 01:42

I want a screenshot of the image on the screen saved into the saved photo library.

20条回答
  •  渐次进展
    2020-11-22 02:29

    Considering a check for retina display use the following code snippet:

    #import  
    
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
        UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(self.window.bounds.size);
    }
    
    [self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *imageData = UIImagePNGRepresentation(image);
    if (imageData) {
        [imageData writeToFile:@"screenshot.png" atomically:YES];
    } else {
        NSLog(@"error while taking screenshot");
    }
    

提交回复
热议问题