我正在使用
以下是我目前想到的解决方案:
AVCaptureVideoDataOutput
和AVCaptureAudioDataOutput
记录视频和音频,在captureOutput:didOutputSampleBuffer:fromConnection:
代理方法中,我想将文本绘制到从视频连接接收到的每个单独的样本缓冲区上。文本大约每帧更改一次(它是一个秒表标签),我希望将其记录在捕获的视频数据之上。以下是我目前想到的解决方案:
//1.
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
//2.
UIImage *textImage = [self createTextImage];
CIImage *maskImage = [CIImage imageWithCGImage:textImage.CGImage];
//3.
CVPixelBufferLockBaseAddress(pixelBuffer, 0);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSDictionary *options = [NSDictionary dictionaryWithObject:(__bridge id)colorSpace forKey:kCIImageColorSpace];
CIImage *inputImage = [CIImage imageWithCVPixelBuffer:pixelBuffer options:options];
//4.
CIFilter *filter = [CIFilter filterWithName:@"CIBlendWithMask"];
[filter setValue:inputImage forKey:@"inputImage"];
[filter setValue:maskImage forKey:@"inputMaskImage"];
CIImage *outputImage = [filter outputImage];
CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
//5.
[self.renderContext render:outputImage toCVPixelBuffer:pixelBuffer bounds:[outputImage extent] colorSpace:CGColorSpaceCreateDeviceRGB()];
//6.
[self.pixelBufferAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:timestamp];
- 我获取像素缓冲区,非常容易。
- 我使用核心图形将文本写入空白的UIImage(这就是
createTextImage
的作用)。我能够验证这一步骤是否有效;我保存了一个带有绘制文本的图像到我的照片中。 - 我从像素缓冲区创建CGImage。
- 我创建了一个CIFilter用于
CIBlendWithMask
,将输入图像设置为从原始像素缓冲区创建的图像,将输入掩模设置为从绘制文本的图像创建的CIImage
。 - 最后,我将滤镜输出图像渲染到像素缓冲区。
CIContext
事先使用[CIContext contextWithOptions:nil];
创建。 - 在所有这些操作之后,我使用适当的时间戳将像素缓冲区附加到我的
pixelBufferAdaptor
中。
录制结束后保存的视频没有任何可见变化,即没有掩模图像绘制到像素缓冲区上。
有人知道我在哪里出错了吗?我已经卡在这里几天了,任何帮助都将不胜感激。
编辑:
- (UIImage *)createTextImage {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height), NO, 1.0);
NSMutableAttributedString *timeStamp = [[NSMutableAttributedString alloc]initWithString:self.timeLabel.text attributes:@{NSForegroundColorAttributeName:self.timeLabel.textColor, NSFontAttributeName: self.timeLabel.font}];
NSMutableAttributedString *countDownString = [[NSMutableAttributedString alloc]initWithString:self.cDownLabel.text attributes:@{NSForegroundColorAttributeName:self.cDownLabel.textColor, NSFontAttributeName:self.cDownLabel.font}];
[timeStamp drawAtPoint:self.timeLabel.center];
[countDownString drawAtPoint:self.view.center];
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return blank;
}
CIContext
对象。 - barndog