【问题标题】:Animate custom CALayer properties inside a CATransaction在 CATransaction 中为自定义 CALayer 属性设置动画
【发布时间】:2011-05-06 13:26:23
【问题描述】:

感谢+ (BOOL)needsDisplayForKey:(NSString *)keyCABasicAnimations,到目前为止,我已经能够为我的 CALayer 子类的自定义属性设置动画。

然而事实证明,链接动画会变得非常棘手,因为所有代码都发生在一个 animationDidStop:finished: 方法中。

所以我想切换到CATransactions,因为它们支持新的块语法,这将允许我使用+ (void)setCompletionBlock:(void (^)(void))block 指定一个完成块。

但在我看来,CATransaction 只能为所谓的“可动画属性”设置动画,并且它不适用于我的自定义图层属性,即使实现了 needsDisplayForKey: 方法也是如此。

那么有没有办法让CALayer 中的自定义属性与CATransaction 一起动画?

编辑: 我的意图是做一些类似的事情:

[CATransaction begin];
[CATransaction setAnimationDuration:0.5];
[CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[CATransaction setCompletionBlock:^{
    NSLog(@"blabla");
}];

myLayer.myProperty = newValue;

[CATransaction commit];

myProperty 值更新为newValue 没有动画。我试图实施 actionForLayer:forKey: 在管理 myLayer 的视图中返回 CABasicAnimation。但是actionForLayer:forKey: 永远不会使用密钥myProperty 调用。是的,myLayer 不是view.layer 而是一个子层,是的,我将myLayer 的委托设置为包含视图。

【问题讨论】:

    标签: iphone properties core-animation catransaction


    【解决方案1】:

    我相信,根据我对一些源代码的阅读,您仍然可以在CATransaction 中使用CABasicAnimation。在[CATransaction begin][CATransaction commit] 之间添加的任何CAAnimations 都应该是事务的一部分。

    [CATransaction begin];
    [CATransaction setAnimationDuration:0.5];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [CATransaction setCompletionBlock:^{
        NSLog(@"blabla");
    }];
    
    // Create the CABasicAnimation using your existing code
    CABasicAnimation *myPropertyAnim = [CABasicAnimation animationWithKeyPath:@"myProperty"];
    // TODO: Setup animation range
    myPropertyAnim.toValue = newValue;
    
    // The CATransaction does not observe arbitrary properties so this fails:
    //myLayer.myProperty = newValue;
    
    // Add the CAAnimation subclass during the CATransaction
    [myLayer addAnimation:myPropertyAnim forKey:@"myKey"];
    
    [CATransaction commit];
    

    抱歉,我现在没有可以轻松测试的项目设置,但我相信它会起作用。

    检查这些网站的代码:

    我引用的代码:

    [CATransaction begin];
    [topLayer addAnimation:topAnimation forKey:@"flip"];
    [bottomLayer addAnimation:bottomAnimation forKey:@"flip"];
    [CATransaction commit];
    

    【讨论】:

    • 我确认它可以工作,但是我感到有点失望的是,自定义属性背后不可能拥有与动画属性相同的魔力。我将运行一些测试,看看如果 CATransaction 的持续时间设置为低于任何封闭的 CAAnimations 的值会发生什么
    【解决方案2】:

    有一个很棒的类叫做CAAnimationBlocks,并解释了here,这是CAAnimation 上的一个类别,它允许您像在UIView 上一样使用完成块。

    您只需调用即可使用它:

    CABasicAnimation myAnimation;
    [myAnimation setCompletion:^(BOOL finished) { // Do something }];
    

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 2011-03-11
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多