How to take a screenshot programmatically on iOS

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

    Two options available at bellow site:

    OPTION 1: using UIWindow (tried and work perfectly)

    // create graphics context with screen size
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    UIGraphicsBeginImageContext(screenRect.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);
    
    // grab reference to our window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    // transfer content into our context
    [window.layer renderInContext:ctx];
    UIImage *screengrab = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    OPTION 2: using UIView

    // grab reference to the view you'd like to capture
    UIView *wholeScreen = self.splitViewController.view;
    
    // define the size and grab a UIImage from it
    UIGraphicsBeginImageContextWithOptions(wholeScreen.bounds.size, wholeScreen.opaque, 0.0);
    [wholeScreen.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *screengrab = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    For retina screen (as DenNukem answer)

    // grab reference to our window
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
        // create graphics context with screen size
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
            UIGraphicsBeginImageContextWithOptions(screenRect.size, NO, [UIScreen mainScreen].scale);
        } else {
            UIGraphicsBeginImageContext(screenRect.size);
            [window.layer renderInContext:UIGraphicsGetCurrentContext()];
        }
    

    for more detail: http://pinkstone.co.uk/how-to-take-a-screeshot-in-ios-programmatically/

提交回复
热议问题