如何在AVPlayerLayer边界上使用加法动画?

时间:2016-05-26 21:07:32

标签: objective-c macos animation avfoundation core-animation

我正在尝试在AVPlayerLayer的界限上进行加法动画。只需将添加剂设置为YES即可打破动画。我需要添加它,以便可以使用不同的动画参数设置宽度和高度的动画。动画关键路径bounds.size.width和bounds.size.height也不起作用。

我可以使用下面的代码为其他CALayer类设置正常的动画,所以我开始怀疑AVPlayerLayer是否有错误。

以下是代码:

AVPlayerLayer *vl; 

// ...


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    NSURL *path = [[NSBundle mainBundle] URLForResource:@"vid" withExtension:@"mp4"]];
    AVPlayer *player = [AVPlayer playerWithURL: path];
    vl = [AVPlayerLayer playerLayerWithPlayer:player];
    vl.videoGravity = AVLayerVideoGravityResize;
//     vl = [CALayer layer]; // a normal calayer animates properly

    vl.backgroundColor = [NSColor redColor].CGColor;
    vl.frame = CGRectMake(200,100,150,100);
    [_window.contentView.layer addSublayer:vl];
}

- (IBAction)animate:(id)sender {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
    animation.fromValue = [NSValue valueWithRect:CGRectMake(0,0,0, 0)];
    animation.toValue = [NSValue valueWithRect:CGRectMake(0,0,240, 60)];
    animation.duration = 4;
    animation.additive = YES;

    [vl addAnimation:animation forKey:nil];
}

这就是它的样子:

enter image description here

红色区域应该是视频播放。

您可以查看我在此处创建的示例项目: https://www.dropbox.com/s/jxuh69wiqdwnuc6/PlayerLayer%20size%20Animation.zip?dl=1

1 个答案:

答案 0 :(得分:0)

CALayer的frame属性是派生属性,取决于图层的位置,anchorPoint,边界和变换。您应该为positionbounds设置动画,而不是为框架设置动画,具体取决于您要完成的效果。

您可以先看一下:

Q: When I try to animate the frame of a CALayer nothing happens. Why?

这也有助于: How to animate the frame of an layer with CABasicAnimation?

这些代码可能对您有所帮助:

NSURL *fileUrl = [NSURL fileURLWithPath:@"yourFilePath"];
AVPlayer *player = [[AVPlayer alloc] initWithURL:fileUrl];

CALayer *superlayer = self.view.layer;
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
[superlayer addSublayer:playerLayer];

[player play];

playerLayer.videoGravity = AVLayerVideoGravityResize;
playerLayer.frame = CGRectMake(10, 200, 320, 200);
playerLayer.position = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);

CGRect startBounds = CGRectMake(10, 200, 200, 150);
CGRect endBounds = CGRectMake(10, 200, 320, 200);

CABasicAnimation * sizeAnimation = [CABasicAnimation animationWithKeyPath:@"bounds"];

sizeAnimation.fromValue = [NSValue valueWithRect:startBounds] ;
sizeAnimation.toValue = [NSValue valueWithRect:endBounds] ;
sizeAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
sizeAnimation.duration = 4;

[playerLayer addAnimation:sizeAnimation forKey:@"bounds"];