iOS - 检测CALayer内容的变化

时间:2014-02-13 14:06:52

标签: ios calayer cakeyframeanimation cadisplaylink

我的CALayer有一个CAKeyFrameAnimation

有没有办法检测CALayer的内容变化?

就像是,每当CALayer的内容(图片)因CAKeyFrameAnimation而发生变化时,我想用AVAudioPlayer播放一个简短的声音。

更新

我是这样解决的。

- (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;
}

当然,不要忘记在不再需要CADisplayLink时使其失效。

1 个答案:

答案 0 :(得分:0)

好像你需要CADisplayLink来完成这项工作,如下所述:Detecting collision, during a CAKeyFrameAnimation

基本上:

  

CADisplayLink对象是一个计时器对象,允许您的应用程序将其绘图与显示的刷新率同步。

     

您的应用程序会创建一个新的显示链接,提供一个目标对象和一个在屏幕更新时调用的选择器。接下来,您的应用程序将显示链接添加到运行循环。

来源:Apple's documentation on CADisplayLink