使用CAKeyframeAnimation在视频上添加动画图层

时间:2015-01-01 17:45:03

标签: objective-c avfoundation calayer cakeyframeanimation avassetexportsession

我试图在我的视频中添加一个叠加层,其中包含一个随时间变化的内容的子图层。因此,我按如下方式将CAKeyframeAnimation添加到图层中:

CALayer *overlayLayer = [CALayer layer];
[overlayLayer setFrame:CGRectMake(0, 0, size.width, size.height)];
[overlayLayer setMasksToBounds:YES];

NSArray *frames = [self.gifImage frames];

CALayer *aLayer = [CALayer layer];
UIImage *firstImage = [frames objectAtIndex:0];
CGFloat nativeWidth = CGImageGetWidth(firstImage.CGImage);
CGFloat nativeHeight = CGImageGetHeight(firstImage.CGImage);
CGRect frame = CGRectMake(0.0, 0.0, nativeWidth, nativeHeight);
aLayer.frame = frame;
aLayer.contents = (id)firstImage.CGImage;
[aLayer setMasksToBounds:YES];

CAKeyframeAnimation *animationSequence = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
animationSequence.calculationMode = kCAAnimationDiscrete;
animationSequence.duration = [self.gifImage totalDuration];
animationSequence.repeatCount = HUGE_VALF;

NSMutableArray *animationSequenceArray = [[NSMutableArray alloc] init];
for (UIImage *image in frames) {
    [animationSequenceArray addObject:(id)image.CGImage];
}

animationSequence.values = animationSequenceArray;
[aLayer addAnimation:animationSequence forKey:@"contents"];
[overlayLayer addSublayer:aLayer];

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];

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

不知何故,当我添加aLayer作为我视图的子图层时,它会正常动画。但是当我将它添加到视频的叠加层时,动画并不起作用。我有什么东西在这里失踪吗?任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

我终于通过将calculationMode更改为kCAAnimationLinear来解决此问题。这似乎是一个愚蠢的问题,但我希望它可能对某人有用。

答案 1 :(得分:0)

如果你使用kCAAnimationDiscrete,这里有一个清单:

  • keyTimes需要一个0-1的值,而不是时间
  • keyTimes必须从0.0开始,以值1.0结束
  • keyTimes必须比动画帧数多一个值