[iOS] 视频添加动效水印实现介绍

简概:

  • 本次文章主要介绍给视频添加动效水印的几种方式,以及实现代码。
  • 使用AVFoundation + CoreAnimation 合成方式
  • 基于Lottie 核心也是 CoreAnimation ,这里我们也可以使用AVFoundation + Lottie 合成方式
  • 我们同样可以使用序列帧资源或者gif资源 来编写一段keyFrameAnination,这里我们就介绍一段 AVFoundation + Gif 合成方式
  • 使用 GPUImageUIElement 将序列帧资源合并在目标资源上
  • 使用 GPUImage 将水印视频合并在目标资源上
  • 如果你有问题,或者对下述文字有任何意见与建议,除了在文章最后留言,还可以在微博阳眼的熊1993上给我留言,或者联系我的邮箱hu-yangyang@qq.com,以及访问我的Github
  • 文章某尾会给到Demo。

视频处理后效果 GIF

原视频.gif
CoreAnimation.gif
Lottie.gif
GIF.gif
GPUImageType1.gif
GPUImageType2.gif

1.使用AVFoundation + CoreAnimation 合成方式

#pragma mark CorAnimation
+ (void)addWaterMarkTypeWithCorAnimationAndInputVideoURL:(NSURL*)InputURL WithCompletionHandler:(void (^)(NSURL* outPutURL, int code))handler{
    NSDictionary *opts = [NSDictionary dictionaryWithObject:@(YES) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVAsset *videoAsset = [AVURLAsset URLAssetWithURL:InputURL options:opts];
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];
    NSError *errorVideo = [NSError new];
    AVAssetTrack *assetVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo]firstObject];
    CMTime endTime = assetVideoTrack.asset.duration;
    BOOL bl = [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, assetVideoTrack.asset.duration)
                                  ofTrack:assetVideoTrack
                                   atTime:kCMTimeZero error:&errorVideo];
    videoTrack.preferredTransform = assetVideoTrack.preferredTransform;
    NSLog(@"errorVideo:%ld%d",errorVideo.code,bl);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *outPutFileName = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",outPutFileName]];
    NSURL* outPutVideoUrl = [NSURL fileURLWithPath:myPathDocs];
    
    CGSize videoSize = [videoTrack naturalSize];
    
    UIFont *font = [UIFont systemFontOfSize:60.0];
    CATextLayer *aLayer = [[CATextLayer alloc] init];
    [aLayer setFontSize:60];
    [aLayer setString:@"H"];
    [aLayer setAlignmentMode:kCAAlignmentCenter];
    [aLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [aLayer setBackgroundColor:[UIColor clearColor].CGColor];
    CGSize textSize = [@"H" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [aLayer setFrame:CGRectMake(240, 470, textSize.width, textSize.height)];
    aLayer.anchorPoint = CGPointMake(0.5, 1.0);

    
    CATextLayer *bLayer = [[CATextLayer alloc] init];
    [bLayer setFontSize:60];
    [bLayer setString:@"E"];
    [bLayer setAlignmentMode:kCAAlignmentCenter];
    [bLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [bLayer setBackgroundColor:[UIColor clearColor].CGColor];
    CGSize textSizeb = [@"E" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [bLayer setFrame:CGRectMake(240 + textSize.width, 470 , textSizeb.width, textSizeb.height)];
    bLayer.anchorPoint = CGPointMake(0.5, 1.0);

    
    CATextLayer *cLayer = [[CATextLayer alloc] init];
    [cLayer setFontSize:60];
    [cLayer setString:@"L"];
    [cLayer setAlignmentMode:kCAAlignmentCenter];
    [cLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [cLayer setBackgroundColor:[UIColor clearColor].CGColor];
    CGSize textSizec = [@"L" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [cLayer setFrame:CGRectMake(240 + textSizeb.width + textSize.width, 470 , textSizec.width, textSizec.height)];
    cLayer.anchorPoint = CGPointMake(0.5, 1.0);

    
    CATextLayer *dLayer = [[CATextLayer alloc] init];
    [dLayer setFontSize:60];
    [dLayer setString:@"L"];
    [dLayer setAlignmentMode:kCAAlignmentCenter];
    [dLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [dLayer setBackgroundColor:[UIColor clearColor].CGColor];
    CGSize textSized = [@"L" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [dLayer setFrame:CGRectMake(240 + textSizec.width+ textSizeb.width + textSize.width, 470 , textSized.width, textSized.height)];
    dLayer.anchorPoint = CGPointMake(0.5, 1.0);
    
    CATextLayer *eLayer = [[CATextLayer alloc] init];
    [eLayer setFontSize:60];
    [eLayer setString:@"O"];
    [eLayer setAlignmentMode:kCAAlignmentCenter];
    [eLayer setForegroundColor:[[UIColor greenColor] CGColor]];
    [eLayer setBackgroundColor:[UIColor clearColor].CGColor];
    CGSize textSizede = [@"O" sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    [eLayer setFrame:CGRectMake(240 + textSized.width + textSizec.width+ textSizeb.width + textSize.width, 470 , textSizede.width, textSizede.height)];
    eLayer.anchorPoint = CGPointMake(0.5, 1.0);

    CABasicAnimation* basicAni = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    basicAni.fromValue = @(0.2f);
    basicAni.toValue = @(1.0f);
    basicAni.beginTime = AVCoreAnimationBeginTimeAtZero;
    basicAni.duration = 2.0f;
    basicAni.repeatCount = HUGE_VALF;
    basicAni.removedOnCompletion = NO;
    basicAni.fillMode = kCAFillModeForwards;
    [aLayer addAnimation:basicAni forKey:nil];
    [bLayer addAnimation:basicAni forKey:nil];
    [cLayer addAnimation:basicAni forKey:nil];
    [dLayer addAnimation:basicAni forKey:nil];
    [eLayer addAnimation:basicAni forKey:nil];
    
    CALayer *parentLayer = [CALayer layer];
    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    videoLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:aLayer];
    [parentLayer addSublayer:bLayer];
    [parentLayer addSublayer:cLayer];
    [parentLayer addSublayer:dLayer];
    [parentLayer addSublayer:eLayer];

    AVMutableVideoComposition* videoComp = [AVMutableVideoComposition videoComposition];
    videoComp.renderSize = videoSize;
    parentLayer.geometryFlipped = true;
    videoComp.frameDuration = CMTimeMake(1, 30);
    videoComp.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    AVMutableVideoCompositionInstruction* instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, endTime);
    AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
    instruction.layerInstructions = [NSArray arrayWithObjects:layerInstruction, nil];
    videoComp.instructions = [NSArray arrayWithObject: instruction];
    
    
    AVAssetExportSession* exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                                      presetName:AVAssetExportPresetHighestQuality];
    exporter.outputURL=outPutVideoUrl;
    exporter.outputFileType = AVFileTypeMPEG4;
    exporter.shouldOptimizeForNetworkUse = YES;
    exporter.videoComposition = videoComp;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            //这里是输出视频之后的操作,做你想做的
            NSLog(@"输出视频地址:%@ andCode:%@",myPathDocs,exporter.error);
            handler(outPutVideoUrl,(int)exporter.error.code);
        });
    }];
}

2.基于Lottie 核心也是 CoreAnimation ,这里我们也可以使用AVFoundation + Lottie 合成方式

  • 与第一段代码不同的地方
LOTAnimationView* animation = [LOTAnimationView animationNamed:@"青蛙"];
    animation.frame = CGRectMake(150 , 340 , 240 , 240 );
    animation.animationSpeed = 5.0 ;
    animation.loopAnimation = YES;
    [animation play];
    
    CALayer *parentLayer = [CALayer layer];
    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    videoLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:animation.layer];

3.我们同样可以使用序列帧资源或者gif资源 来编写一段keyFrameAnination,这里我们就介绍一段 AVFoundation + Gif 合成方式

  • 与第一段代码不同的地方是将gif 转成layer 的KEYFrameAnimation
CALayer *gifLayer1 = [[CALayer alloc] init];
    gifLayer1.frame = CGRectMake(150 , 340 , 298 , 253 );
    CAKeyframeAnimation *gifLayer1Animation = [WatermarkEngine animationForGifWithURL:[[NSBundle mainBundle] URLForResource:@"雪人完成_1" withExtension:@"gif"]];
    gifLayer1Animation.beginTime = AVCoreAnimationBeginTimeAtZero;
    gifLayer1Animation.removedOnCompletion = NO;
    [gifLayer1 addAnimation:gifLayer1Animation forKey:@"gif"];
    
    
    CALayer *parentLayer = [CALayer layer];
    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    videoLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:gifLayer1];
+ (CAKeyframeAnimation *)animationForGifWithURL:(NSURL *)url {
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    
    NSMutableArray * frames = [NSMutableArray new];
    NSMutableArray *delayTimes = [NSMutableArray new];
    
    CGFloat totalTime = 0.0;
    CGFloat gifWidth;
    CGFloat gifHeight;
    
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    
    // get frame count
    size_t frameCount = CGImageSourceGetCount(gifSource);
    for (size_t i = 0; i < frameCount; ++i) {
        // get each frame
        CGImageRef frame = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        [frames addObject:(__bridge id)frame];
        CGImageRelease(frame);
        
        // get gif info with each frame
        NSDictionary *dict = (NSDictionary*)CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(gifSource, i, NULL));
        NSLog(@"kCGImagePropertyGIFDictionary %@", [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary]);
        
        // get gif size
        gifWidth = [[dict valueForKey:(NSString*)kCGImagePropertyPixelWidth] floatValue];
        gifHeight = [[dict valueForKey:(NSString*)kCGImagePropertyPixelHeight] floatValue];
        
        // kCGImagePropertyGIFDictionary中kCGImagePropertyGIFDelayTime,kCGImagePropertyGIFUnclampedDelayTime值是一样的
        NSDictionary *gifDict = [dict valueForKey:(NSString*)kCGImagePropertyGIFDictionary];
        [delayTimes addObject:[gifDict valueForKey:(NSString*)kCGImagePropertyGIFUnclampedDelayTime]];
        
        totalTime = totalTime + [[gifDict valueForKey:(NSString*)kCGImagePropertyGIFUnclampedDelayTime] floatValue];
        
        //        CFRelease((__bridge CFTypeRef)(dict));
        //        CFRelease((__bridge CFTypeRef)(dict));
    }
    if (gifSource) {
        CFRelease(gifSource);
    }
    
    NSMutableArray *times = [NSMutableArray arrayWithCapacity:3];
    CGFloat currentTime = 0;
    NSInteger count = delayTimes.count;
    for (int i = 0; i < count; ++i) {
        [times addObject:[NSNumber numberWithFloat:(currentTime / totalTime)]];
        currentTime += [[delayTimes objectAtIndex:i] floatValue];
    }
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
    for (int i = 0; i < count; ++i) {
        [images addObject:[frames objectAtIndex:i]];
    }
    
    animation.keyTimes = times;
    animation.values = images;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = totalTime;
    animation.repeatCount = HUGE_VALF;
    
    return animation;
}

4.使用 GPUImage 将水印视频合并在目标资源上

#pragma mark GPUImage TWO VIDEO INPUT
+ (void)addWaterMarkTypeWithGPUImageAndInputVideoURL:(NSURL*)InputURL AndWaterMarkVideoURL:(NSURL*)InputURL2 WithCompletionHandler:(void (^)(NSURL* outPutURL, int code))handler{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *outPutFileName = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",outPutFileName]];
    NSURL* outPutVideoUrl = [NSURL fileURLWithPath:myPathDocs];
    
    GPUImageMovie* movieFile = [[GPUImageMovie alloc] initWithURL:InputURL];
    GPUImageMovie* movieFile2 = [[GPUImageMovie alloc] initWithURL:InputURL2];
    GPUImageScreenBlendFilter* filter =  [[GPUImageScreenBlendFilter alloc] init];
    [movieFile addTarget:filter];
    [movieFile2 addTarget:filter];
    
    GPUImageMovieWriter* movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:outPutVideoUrl size:CGSizeMake(540, 960) fileType:AVFileTypeQuickTimeMovie outputSettings:    @
                                        {
                                        AVVideoCodecKey: AVVideoCodecH264,
                                        AVVideoWidthKey: @540,   //Set your resolution width here
                                        AVVideoHeightKey: @960,  //set your resolution height here
                                        AVVideoCompressionPropertiesKey: @
                                            {
                                                //2000*1000  建议800*1000-5000*1000
                                                //AVVideoAverageBitRateKey: @2500000, // Give your bitrate here for lower size give low values
                                            AVVideoAverageBitRateKey: @5000000,
                                            AVVideoProfileLevelKey: AVVideoProfileLevelH264HighAutoLevel,
                                            AVVideoAverageNonDroppableFrameRateKey: @30,
                                            },
                                        }
                                        ];
    [filter  addTarget:movieWriter];
    AVAsset* videoAsset = [AVAsset assetWithURL:InputURL];
    AVAssetTrack *assetVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo]firstObject];
    movieWriter.transform = assetVideoTrack.preferredTransform;
    //    [movie enableSynchronizedEncodingUsingMovieWriter:movieWriter];
    [movieWriter startRecording];
    [movieFile startProcessing];
    [movieFile2 startProcessing];
    [movieWriter setCompletionBlock:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"movieWriter Completion");
            
            handler(outPutVideoUrl,1);
        });

    }];
    
}

5.使用 GPUImageUIElement 将序列帧资源合并在目标资源上

#pragma mark GPUImageUIElement
+ (void)addWaterMarkTypeWithGPUImageUIElementAndInputVideoURL:(NSURL*)InputURL WithCompletionHandler:(void (^)(NSURL* outPutURL, int code))handler{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *outPutFileName = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",outPutFileName]];
    NSURL* outPutVideoUrl = [NSURL fileURLWithPath:myPathDocs];
    
    GPUImageMovie* movieFile = [[GPUImageMovie alloc] initWithURL:InputURL];

    

    NSValue *value = [NSValue valueWithCGRect:CGRectMake([UIScreen mainScreen].bounds.size.width/2.0 - (332 /2.0) , [UIScreen mainScreen].bounds.size.height/2.0 - (297 /2.0) , 332 , 297 )];
    NSValue *value2 = [NSValue valueWithCGAffineTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
    GPUImageFilterGroup* filter =  [WatermarkEngine addWatermarkWithResourcesNames:@[@"雨天青蛙"] Andframes:@[value] AndTransform:@[value2] AndLabelViews:@[view]];
    [movieFile addTarget:filter];

    
    GPUImageMovieWriter* movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:outPutVideoUrl size:CGSizeMake(540, 960) fileType:AVFileTypeQuickTimeMovie outputSettings:    @
                                        {
                                        AVVideoCodecKey: AVVideoCodecH264,
                                        AVVideoWidthKey: @540,   //Set your resolution width here
                                        AVVideoHeightKey: @960,  //set your resolution height here
                                        AVVideoCompressionPropertiesKey: @
                                            {
                                                //2000*1000  建议800*1000-5000*1000
                                                //AVVideoAverageBitRateKey: @2500000, // Give your bitrate here for lower size give low values
                                            AVVideoAverageBitRateKey: @5000000,
                                            AVVideoProfileLevelKey: AVVideoProfileLevelH264HighAutoLevel,
                                            AVVideoAverageNonDroppableFrameRateKey: @30,
                                            },
                                        }
                                        ];
    [filter  addTarget:movieWriter];
    AVAsset* videoAsset = [AVAsset assetWithURL:InputURL];
    AVAssetTrack *assetVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo]firstObject];
    movieWriter.transform = assetVideoTrack.preferredTransform;
    //    [movie enableSynchronizedEncodingUsingMovieWriter:movieWriter];
    [movieWriter startRecording];
    [movieFile startProcessing];
    [movieWriter setCompletionBlock:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"movieWriter Completion");
            
            handler(outPutVideoUrl,1);
        });
        
    }];
}
+ (GPUImageFilterGroup*) addWatermarkWithResourcesNames:(NSArray* )resourcesNames Andframes:(NSArray*)frams AndTransform:(NSArray*)transforms AndLabelViews:(NSArray*)labelViews{
  __block int currentPicIndex = 0;
  CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
  UIView* temp = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
  [temp setContentScaleFactor:[[UIScreen mainScreen] scale]];
  __block UIImageView* waterImageView1 = [[UIImageView alloc] init];
  __block UIImageView* waterImageView2 = [[UIImageView alloc] init];
  __block UIImageView* waterImageView3 = [[UIImageView alloc] init];
  for (int index = 0 ; index < resourcesNames.count ; index++) {
    if (index == 0) {
      waterImageView1.frame = [frams[index] CGRectValue];
      UIImage* tempImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_%05d",resourcesNames[index],currentPicIndex] ofType:@"png"]];
      waterImageView1.image = tempImage;
      waterImageView1.transform = [transforms[index] CGAffineTransformValue];
      [temp addSubview:waterImageView1];
      [temp addSubview:labelViews[index]];
    }else if (index == 1){
      waterImageView2.frame = [frams[index] CGRectValue];
      UIImage* tempImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_%05d",resourcesNames[index],currentPicIndex] ofType:@"png"]];
      waterImageView2.image = tempImage;
      waterImageView2.transform = [transforms[index] CGAffineTransformValue];
      [temp addSubview:waterImageView2];
      [temp addSubview:labelViews[index]];
    }else{
      waterImageView3.frame = [frams[index] CGRectValue];
      UIImage* tempImage = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_%05d",resourcesNames[index],currentPicIndex] ofType:@"png"]];
      waterImageView3.image = tempImage;
      waterImageView3.transform = [transforms[index] CGAffineTransformValue];
      [temp addSubview:waterImageView3];
      [temp addSubview:labelViews[index]];
    }
    

  }
  
  
  

  
   GPUImageFilterGroup* filterGroup = [[GPUImageFilterGroup alloc] init];
  
  GPUImageUIElement *uiElement = [[GPUImageUIElement alloc] initWithView:temp];
  GPUImageTwoInputFilter* blendFilter = [[GPUImageTwoInputFilter alloc] initWithFragmentShaderFromString:[WatermarkEngine loadShader:@"AlphaBlend_Normal" extension:@"frag"]];
  GPUImageFilter* filter = [[GPUImageFilter alloc] init];

  GPUImageFilter* uiFilter = [[GPUImageFilter alloc] init];
  [uiElement addTarget:uiFilter];
//  [uiFilter setInputRotation:kGPUImageRotateLeft atIndex:0];
  
  [filter addTarget:blendFilter];
  [uiFilter addTarget:blendFilter];
  
  
  [filterGroup addFilter:filter];
  [filterGroup addFilter:uiFilter];
  [filterGroup addFilter:blendFilter];

  
  [filterGroup setInitialFilters:@[filter]];
  [filterGroup setTerminalFilter:blendFilter];
  // 71
  //    __unsafe_unretained typeof(self) this = self;
  [filter setFrameProcessingCompletionBlock:^(GPUImageOutput * filter, CMTime frameTime) {
    currentPicIndex += 1;
    
    for (int index = 0 ; index < resourcesNames.count ; index++) {
      if (index == 0) {
        waterImageView1.image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_%05d",resourcesNames[index],currentPicIndex] ofType:@"png"]];
      }else if (index == 1){
        waterImageView2.image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_%05d",resourcesNames[index],currentPicIndex] ofType:@"png"]];
      }else{
        waterImageView3.image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@_%05d",resourcesNames[index],currentPicIndex] ofType:@"png"]];
      }
      
      
    }
    
    
    if (currentPicIndex == 89) {
      currentPicIndex = 0;
    }
    
    [uiElement update];
  }];
  
  return filterGroup;
  
}
+ (NSString * _Nonnull)loadShader:(NSString *)name extension:(NSString *)extenstion {
    NSURL *url = [[NSBundle mainBundle] URLForResource:name withExtension:extenstion];
    return [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
}

demo传送门:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,126评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,254评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,445评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,185评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,178评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,970评论 1 284
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,276评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,927评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,400评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,883评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,997评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,646评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,213评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,204评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,423评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,423评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,722评论 2 345

推荐阅读更多精彩内容