I have a CALayer
which has a CAKeyFrameAnimation
.
Is there a way to detect the change of contents of CALayer
?
It's like, whenever the contents (image) of CALayer
is changed due to CAKeyFrameAnimation
, I want to play a short sound with AVAudioPlayer
.
UPDATE
I solved it by doing like this.
- (void) viewDidLoad
{
// init CADisplayLink to catch the changing moment
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(checkContents:)];
[displayLink setFrameInterval:6] // checking by every 0.1 sec (6 frames)
[displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
- (void) checkContents:(CADisplayLink *) sender;
{
// _newImage and _oldImage are class variables. (UIImage)
// animatingView is a `UIImageView` where its layer's contents is being changed by `CAKeyFrameAnimation`
CALayer *presentLayer = [animatingView.layer presentationLayer];
_newImage = presentLayer.contents;
if ( ![_newimage isEqual:_oldImage] )
{
NSLog(@"Image changed! From %@ to %@", _oldImage, _newImage);
}
_oldImage = _newImage;
}
of course, do not forget to invalidate CADisplayLink
when it is no more needed.
Seems like you need a CADisplayLink
to do the job, like described here: Detecting collision, during a CAKeyFrameAnimation
Basically:
A CADisplayLink object is a timer object that allows your application to synchronize its drawing to the refresh rate of the display.
Your application creates a new display link, providing a target object and a selector to be called when the screen is updated. Next, your application adds the display link to a run loop.