Search code examples
iosxcodecore-animationavfoundation

Animation doesn't begin when using AVSynchronizedLayer


I've set up a project as a test using AVSyncronizedLayer to move a red line (CALayer) across the screen as a movie plays.

When doing this I referenced the answer given here and have included that solution, but the animation doesn't start when the video does.

If anyone has any ideas where I'm going wrong that would be really helpful. The code is:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//create the red line sublayer
redLine = [CALayer layer];
redLine.backgroundColor = [UIColor redColor].CGColor;
redLine.frame = CGRectMake(engravingControl.frame.origin.x, engravingControl.center.y - (engravingControl.frame.size.height/2), 3, engravingControl.frame.size.height);


//create the AVplayer object
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"IMG_1306" withExtension:@"mov"];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];

AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame = CGRectMake(0, 0,400,300);
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

//add the subViews
[self.view.layer addSublayer:playerLayer];
[self.view.layer addSublayer:redLine];

CABasicAnimation *redLineMove;  
redLineMove=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
redLineMove.duration=10;
redLineMove.fromValue=[NSNumber numberWithFloat:engravingControl.frame.origin.x];
redLineMove.toValue=[NSNumber numberWithFloat:engravingControl.frame.size.width + engravingControl.frame.origin.x];
redLineMove.beginTime = AVCoreAnimationBeginTimeAtZero;


//create the sync layer
AVSynchronizedLayer *syncLayer = [AVSynchronizedLayer     synchronizedLayerWithPlayerItem:playerItem];
[syncLayer addSublayer:redLine];
[redLine addAnimation:redLineMove forKey:@"redLineMove"];

[self.view.layer addSublayer:syncLayer];

[player play];

}

Solution

  • I discovered a solution to this. If you don't have the following line of code:

    animation.removedOnCompletion = NO;
    

    Then the animation never starts (I presume it is removed by CA before the movie starts to play).

    Add that in, and it works as you would expect.