问题
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:
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];
来源:https://stackoverflow.com/questions/26937656/ios-taking-screenshot-presenting-video-ipad