如何以编程方式对视频文件加水印

时间:2018-07-10 14:38:49

标签: ios objective-c ipad avfoundation

我有一个用户从iPhone相机录制的视频文件。然后,我想生成一个新的视频文件,其中包括一个位于其顶部的PNG层。

如何在Objective-C中完成这样的任务?

我很高兴产生能显示如何录制视频文件的代码,但是您可以假定它是普通的.mov文件。

非常感谢您!

1 个答案:

答案 0 :(得分:1)

在本地保存文件之前,请创建一个CATextLayer并将其附加到视频。我相信这段代码会对您为我的应用程序编写的代码有帮助。

- (void)applyVideoEffectsToComposition:(AVMutableVideoComposition *)composition size:(CGSize)size
{
    NSArray *fieldsArray = overlayFieldsArray;
    // 1 - Set up the text layer
    CATextLayer *subtitle1Text = [[CATextLayer alloc] init];
    subtitle1Text.wrapped=YES;
    subtitle1Text.alignmentMode = kCAAlignmentLeft;
    [subtitle1Text setFont:@"Helvetica-Bold"];
    [subtitle1Text setFontSize:textSize];
    [subtitle1Text setFrame:CGRectMake(0, 0, size.width, fieldsArray.count*textSize+20) ];


    NSMutableString *layerText = [NSMutableString stringWithCapacity:0];

    for(NSDictionary *fieldDictionary in fieldsArray){

        [layerText appendFormat:@" %@ :",[[fieldDictionary allKeys] objectAtIndex:0]];

        [layerText appendFormat:@" %@ \n",[_candidateDictionary valueForKey:[[fieldDictionary allValues] objectAtIndex:0]]];
    }


    [subtitle1Text setString:layerText];

    [subtitle1Text setForegroundColor:[[UIColor colorForText] CGColor]];

    // 2 - The usual overlay
    CALayer *overlayLayer = [CALayer layer];
    overlayLayer.backgroundColor = [UIColor colorForLayer].CGColor;
    overlayLayer.opacity=0.5f;
    CGSize maximumSize = CGSizeMake(600, 600);
    UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:textSize];
    CGSize layerTextSize = [layerText sizeWithFont:myFont
                                 constrainedToSize:maximumSize
                                     lineBreakMode:UILineBreakModeWordWrap];
    overlayLayer.frame = CGRectMake(10, 0, layerTextSize.width*1.1, fieldsArray.count*textSize+20);
    [overlayLayer setMasksToBounds:YES];

    [overlayLayer addSublayer:subtitle1Text];

    CALayer *parentLayer = [CALayer layer];

    CALayer *videoLayer = [CALayer layer];
    videoLayer.frame = CGRectMake(0, 0, size.width, size.height);
    [parentLayer addSublayer:videoLayer];


    parentLayer.frame = CGRectMake(10, 0, layerTextSize.width*1.1, fieldsArray.count*textSize+20);
    [parentLayer addSublayer:overlayLayer];



    composition.animationTool = [AVVideoCompositionCoreAnimationTool
                                 videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];

}