How to take a screenshot programmatically on iOS

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

    Just a small contribution, I've done this with a button but the pressing also means the button is captured pressed. So first I unhighlight.

    - (IBAction)screenShot:(id)sender {
        // Unpress screen shot button
        screenShotButton.highlighted = NO;
    
        // create graphics context with screen size
        CGRect screenRect = [[UIScreen mainScreen] bounds];
    
        if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
            UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
        } else {
            UIGraphicsBeginImageContext(self.view.bounds.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();
    
        // save screengrab to Camera Roll
        UIImageWriteToSavedPhotosAlbum(screengrab, nil, nil, nil);
    }
    

    I got the main body of the code from: http://pinkstone.co.uk/how-to-take-a-screeshot-in-ios-programmatically/ where I used option 1, option 2 didn't seem to work for me. Added the adjustments for Rentina screen sizes from this thread, and the unhighlighting of the screenShotButton. The view I'm using it on is a StoryBoarded screen of buttons and labels and with several UIView added later via the program.

    0 讨论(0)
  • 2020-11-22 02:32

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