转载自: http://www.jianshu.com/p/8e9234a70955
1.截取当前屏幕,导航栏不见。
方法:
- (UIImage*)screenView:(UIView *)view{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(view.frame), CGRectGetHeight(view.frame)), NO, 1);
[view drawViewHierarchyInRect:CGRectMake(0, 0, CGRectGetWidth(view.frame), CGRectGetHeight(view.frame)) afterScreenUpdates:NO];
UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return snapshot;
}
使用:
UIImage *image = [self screenView: [UIApplication sharedApplication].keyWindow ];
UIImageView *snapView = [[UIImageView alloc] initWithImage:image];
snapView.alpha = 1.0f;
snapView.frame = [UIApplication sharedApplication].keyWindow.frame;
2.AVplay 视频流的截屏
发现视频流的截屏是黑色,而不是当前帧的画面
#pragma mark - 截图 点击事件 方法
- (IBAction)didClickSnip:(UIBarButtonItem *)sender {
self.imgGenerator = [[AVAssetImageGenerator alloc]initWithAsset:self.playerItem.asset];
self.imgGenerator.requestedTimeToleranceBefore = kCMTimeZero;
self.imgGenerator.requestedTimeToleranceAfter = kCMTimeZero;
//第一种 --截图方法
// CGImageRef imgRef = [self.imgGenerator copyCGImageAtTime:self.player.currentTime actualTime:NULL error:nil];
//
// self.snipImageView.image = [UIImage imageWithCGImage:imgRef];
//第二种 --截图方法
NSValue *value = [NSValue valueWithCMTime:self.player.currentTime];
[self.imgGenerator generateCGImagesAsynchronouslyForTimes:@[value] completionHandler:^(CMTime requestedTime, CGImageRef _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
//这里先用OC对象对C变量强引用,保证在回到主线程中不会被释放掉
UIImage *img = [UIImage imageWithCGImage:image];
dispatch_async(dispatch_get_main_queue(), ^{
self.snipImageView.image = img;
});
}];
}
3.AVplay 获取当前帧图片
/**
Description
获取当前帧图片
@return return value description
*/
//获取输出流的地址
@property(nonatomic, strong) AVPlayerItemVideoOutput * videoOutPut;
-(UIImage*)getScreenShotImg{
CMTime time = [self.videoOutPut itemTimeForHostTime:CACurrentMediaTime()];
if (0 == time.value) {
return nil;
}
//截取到对应的图片
if ([self.videoOutPut hasNewPixelBufferForItemTime:time]) {
CVPixelBufferRef lastSnapshotPixelBuffer = [self.videoOutPut copyPixelBufferForItemTime:time itemTimeForDisplay:NULL];
CIImage *ciImage = [CIImage imageWithCVPixelBuffer:lastSnapshotPixelBuffer];
CIContext *context = [CIContext contextWithOptions:NULL];
CGRect rect = CGRectMake(0,
0,
CVPixelBufferGetWidth(lastSnapshotPixelBuffer),
CVPixelBufferGetHeight(lastSnapshotPixelBuffer));
CGImageRef cgImage = [context createCGImage:ciImage fromRect:rect];
self.screenShotImg = [UIImage imageWithCGImage:cgImage];
//当前帧的画面
CGImageRelease(cgImage);
return self.screenShotImg;
}
return nil;
}