无论是使用 UIImagePicker 控制器还是 AVFoundation,我都需要捕获或录制视频,其中不仅应记录相机输出,还应记录叠加子视图。我已经看到很多将叠加图像添加到相机预览的示例,但我想要的不仅是叠加图像或文本预览,而且是在最终视频输出中实际记录叠加。
// 添加图形层
CALayer *theDonut = [CALayer layer];
theDonut.bounds = CGRectMake(50,50, 150, 150);
theDonut.cornerRadius = 50/2;
theDonut.backgroundColor = [UIColor clearColor].CGColor;
theDonut.borderWidth = 50/5;
theDonut.borderColor = [UIColor orangeColor].CGColor;
// 设置视频预览层
videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:capSession];
videoPreviewLayer.frame = videoPreview.bounds;
videoPreviewLayer.backgroundColor = [UIColor blackColor].CGColor;
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
videoPreview.layer.masksToBounds = YES;
[videoPreview.layer addSublayer:videoPreviewLayer];
[videoPreview.layer addSublayer:theDonut];
// 添加文本层
UIFont *font = [UIFont fontWithName:@"MarkerFelt-Thin" size:40.0];
CGSize maxSize = CGSizeMake(480, 10000.0);
CGSize labelSize = [@"Test Text" sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect labelFrame = CGRectMake(50.0, 10.0, labelSize.width, labelSize.height);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
label.font = font;
label.text = @"Test Text";
label.numberOfLines = 0;
[videoPreview addSubview:label];
// 甚至添加按钮覆盖!!!
UIButton *snap = [UIButton buttonWithType:UIButtonTypeCustom];
[snap setImage:[UIImage imageNamed:@"takePic"]
forState:UIControlStateNormal];
[snap addTarget:self
action:@selector(pickerCameraSnap:)
forControlEvents:UIControlEventTouchUpInside];
snap.frame = CGRectMake(74, 370, 178, 37);
[videoPreview addSubview:snap];
// 8) Commit session configuration
// 9) Start running capture session
// ========================================
[capSession commitConfiguration];
[capSession startRunning];
//Make sure video is not recording
[[videoDataOutput connectionWithMediaType:AVMediaTypeVideo] setEnabled:NO];
此示例是从此示例代码修改的 - 它确实将文本和绘图添加到视频预览中,但不会将它们记录在最终输出文件中。