iOS: taking screenshot presenting video ipad

630 views Asked by At

I'm trying to take screenshot playing video but the screenshot always is showing blank. This is my code:

UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data = UIImageJPEGRepresentation(viewImage, 1.0);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.jpg"];
    [data writeToFile:filePath atomically:YES];

I'm using AVPlayer/AVPlayerLayer to play the video.

Any of you knows why this happening? or if I need to do something special with video to be able to take the screenshot?

I'll really appreciate your help.

1

There are 1 answers

0
user2924482 On

I found a solution to my problem:

AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:[self.player.currentItem asset]];
    CGImageRef ref = [imageGenerator copyCGImageAtTime:self.player.currentItem.currentTime actualTime:nil error:nil];
    UIImage *viewImage = [UIImage imageWithCGImage:ref];
    CGImageRelease(ref);
    NSData *data = UIImageJPEGRepresentation(viewImage, 1.0);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.jpg"];
    [data writeToFile:filePath atomically:YES];