How to take a screenshot programmatically on iOS

前端 未结 20 2117
一生所求
一生所求 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:21

    I'm answering this question as it's a highly viewed, and there are many answers out there plus there's Swift and Obj-C.

    Disclaimer This is not my code, nor my answers, this is only to help people that land here find a quick answer. There are links to the original answers to give credit where credit is due!! Please honor the original answers with a +1 if you use their answer!


    Using QuartzCore

    #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");
    }
    

    In Swift

    func captureScreen() -> UIImage
    {
    
        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0);
    
        self.view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
    
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    
        UIGraphicsEndImageContext()
    
        return image
    }
    

    Note: As the nature with programming, updates may need to be done so please edit or let me know! *Also if I failed to include an answer/method worth including feel free to let me know as well!

提交回复
热议问题