观察图层'strokeEnd'动画事件

Observe layer 'strokeEnd' animation event

我想在动画开始时观察 strokeEnd 关键路径。但是不行,我哪里错了?

- (void)addAnimation {
    // do animation
    CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    drawAnimation.duration            = 3.f;
    drawAnimation.repeatCount         = 1.0;
    drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    drawAnimation.toValue   = [NSNumber numberWithFloat:0.5f];
    drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    drawAnimation.fillMode = kCAFillModeForwards;
    drawAnimation.removedOnCompletion = NO;
    [self.progressLayer addAnimation:drawAnimation forKey:@"drawCircleAnimation"];
    [self.progressLayer addObserver:self forKeyPath:@"strokeEnd" options:NSKeyValueObservingOptionNew context:NULL]; // 监听position

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"change:%@",change);
    // not called here...
}

您无法在动画 "in flight" 那样时观察到动画属性的变化。 属性 实际上设置为动画开始时的结束值。然后有一个 "presentation layer" 放在视图的常规层之上,动画发生在该层上。

您最好设置一个 CADisplayLink 计时器(一个与屏幕刷新率同步的轻量级计时器)并查询 属性表示层动画(layer.presentationLayer.strokeEnd,在你的例子中。)