AVPlayer和Video的截图

我正在尝试在更大的视图中截取AVPlayer的截图。 我只想构build一个testing框架,所以私有APIs或任何方法都是好的,因为在发布到AppStore时框架将不会被包含。

我已经尝试过使用

  • UIGetScreenImage() :在模拟器上运行良好,但不在设备上
  • snapshotviewafterscreenupdates :它显示的视图,但我不能从中创build一个UIImage
  • drawViewInHierarchyrenderInContext将不适用于AVPlayer
  • 我不想使用AVAssetGenerator或从video获取图像,很难得到一个好的坐标或video播放器作为其他视图的子视图

我知道你不想使用AVAssetImageGenerator,但我也研究了这个广泛的,我相信目前唯一的解决scheme是使用AVAssetImageGenerator。 如果你说得到正确的坐标并不难,因为你应该能够得到你的球员的当前时间。 在我的应用程序下面的代码完美的作品:

 -(UIImage *)getAVPlayerScreenshot { AVURLAsset *asset = (AVURLAsset *)self.playerItem.asset; AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset]; imageGenerator.requestedTimeToleranceAfter = kCMTimeZero; imageGenerator.requestedTimeToleranceBefore = kCMTimeZero; CGImageRef thumb = [imageGenerator copyCGImageAtTime:self.playerItem.currentTime actualTime:NULL error:NULL]; UIImage *videoImage = [UIImage imageWithCGImage:thumb]; CGImageRelease(thumb); return videoImage; } 

AVPlayer使用GPU渲染video,因此无法使用核心graphics方法捕获它。

但是,可以使用AVAssetImageGenerator捕获图像,您需要指定CMTime。

如果你想采取当前屏幕的屏幕截图,只需调用以下方法在任何给你的图像对象的行动事件。

 -(UIImage *) screenshot { UIGraphicsBeginImageContext(self.view.bounds.size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *sourceImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //now we will position the image, X/Y away from top left corner to get the portion we want UIGraphicsBeginImageContext(sourceImage.size); [sourceImage drawAtPoint:CGPointMake(0, 0)]; UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //To write image on divice. //UIImageWriteToSavedPhotosAlbum(croppedImage,nil, nil, nil); return croppedImage; } 

希望这会帮助你。

 CGRect grabRect = CGRectMake(0,0,320,568);// size you want to take screenshot of. if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { UIGraphicsBeginImageContextWithOptions(grabRect.size, NO, [UIScreen mainScreen].scale); } else { UIGraphicsBeginImageContext(grabRect.size); } CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(ctx, -grabRect.origin.x, -grabRect.origin.y); [self.view.layer renderInContext:ctx]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();