在做iOS视频相关的开发的时候,遇到了一点点坑。
iOS视频添加水印,你首先会想到使用 animationTool , 苹果官方是这样写的
A video composition describes, for any time in the aggregate time range of its instructions, the number and IDs of video tracks that are to be used in order to produce a composed video frame corresponding to that time. When AV Foundation’s built-in video compositor is used, the instructions an AVVideoComposition comprises can specify a spatial transformation, an opacity value, and a cropping rectangle for each video source, and these can vary over time via simple linear ramping functions.
然后就按照步骤实现就可以了
// 1 - set up the overlay
CALayer *overlayLayer = [CALayer layer];
[overlayLayer setContents:(id)[image CGImage]];
overlayLayer.frame = CGRectMake(0, 0, size.width, size.height);
[overlayLayer setMasksToBounds:YES];
// 2 - set up the parent layer
CALayer *parentLayer = [CALayer layer];
CALayer *videoLayer = [CALayer layer];
parentLayer.frame = CGRectMake(0, 0, size.width, size.height);
videoLayer.frame = CGRectMake(0, 0, size.width, size.height);
[parentLayer addSublayer:videoLayer];
[parentLayer addSublayer:overlayLayer];
// 3 - apply magic
composition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer
但是在iOS 10下发现,有时候这个方法导出的视频不能立即播放,要等一会儿视频才能播放,于是就使用了下面的这个接口
CIFilter *watermarkFilter = [CIFilter filterWithName:@"CISourceOverCompositing"];
mainVideoComposition= [AVMutableVideoComposition videoCompositionWithAsset:mixComposition applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {
CIImage *watermarkImage = [[CIImage alloc] initWithCGImage:image.CGImage];
CIImage *source = request.sourceImage;
[watermarkFilter setValue:source forKey:kCIInputBackgroundImageKey];
[watermarkFilter setValue:[watermarkImage imageByApplyingTransform:CGAffineTransformMakeScale(source.extent.size.width/watermarkImage.extent.size.width, source.extent.size.height/watermarkImage.extent.size.height)] forKey:kCIInputImageKey];
[request finishWithImage:watermarkFilter.outputImage context:nil];
}];