kotowo
3/30/2016 - 12:53 AM

ScreenCapture.m

- (void)foo
{
    UIImage* image = [self screenshot];
    UIImageWriteToSavedPhotosAlbum(
        image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (UIImage*)screenshot
{
    UIScreen* mainScreen = [UIScreen mainScreen];
    CGSize imageSize = mainScreen.bounds.size;
    float scale = mainScreen.scale;
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, scale);

    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow* window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] ||
            [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, [window center].x, [window center].y);
            CGContextConcatCTM(context, [window transform]);
            CGContextTranslateCTM(
                context, -[window bounds].size.width * [[window layer] anchorPoint].x,
                -[window bounds].size.height * [[window layer] anchorPoint].y);
            [[window layer] renderInContext:context];
            CGContextRestoreGState(context);
        }
    }
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)image:(UIImage*)image
    didFinishSavingWithError:(NSError*)error
                 contextInfo:(void*)contextInfo
{
    if (!error) {
        NSLog(@"%@", error);
    }
}

//- (UIImage *)screenshot2 {
//
//  CGImageRef imgRef = UIGetScreenImage();
//  UIImage *img = [UIImage imageWithCGImage:imgRef];
//
//  return img;
//}
//

- (UIImage*)screenshot3
{
    UIScreen* mainScreen = [UIScreen mainScreen];
    CGSize imageSize = mainScreen.bounds.size;
    float scale = mainScreen.scale;
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, scale);
    
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}