【问题标题】:How do I make a layer maintain the final value of a CABasicAnimation如何使图层保持 CABasicAnimation 的最终值
【发布时间】:2013-04-25 22:49:45
【问题描述】:

考虑以下动画:

CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.0;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
pathAnimation.removedOnCompletion = NO;
pathAnimation.delegate = self;

这实际上将动画从一端到另一端的图层绘制。问题是一旦动画完成,strokeEnd 属性会重置回 0(最初设置的位置)。如何使最终值“坚持”?

我试图在 animationDidStop 委托方法中改变它。这主要是有效的,但可能会导致 strokeEnd 在 0 处短暂闪烁,即使放在 CATransaction 中以禁用动画也是如此。我也玩过additivecumulative 属性,但无济于事。有什么建议吗?

【问题讨论】:

标签: ios core-animation calayer


【解决方案1】:

您只需自己将strokeEnd 属性设置为其最终值!像这样:

// your current code (stripped of unnecessary stuff)

CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.0;
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];

// just add this to it:

theLayer.strokeEnd = 1;

// and now add the animation to theLayer

如果strokeEnd 是可隐式动画的(这样那条线本身就会产生动画),我们将首先关闭隐式动画:

[CATransaction setDisableActions:YES];
theLayer.strokeEnd = 1;

请注意,您的pathAnimation.removedOnCompletion = NO; 是错误的,另一个答案的kCAFillModeForwards 也是如此。两者都是基于对 Core Animation 工作原理的误解。

【讨论】:

  • 感谢您的澄清,正如我在回答中的评论中所写,我一直认为设置 fillMode 会导致模型层在动画结束时更新。只是要知道,什么时候应该使用 fillMode 和 removedOnCompletion=NO ?我正在考虑,但找不到示例。
  • 它们在复杂的分组动画中很有用。再次,请参阅上面提到的我的书(在 fillMode 上搜索该章节)。关键是这个技巧是一个巨大的误解,不幸的是在互联网上流传开来。甚至苹果也有一个例子,他们对此给人留下了错误的印象(节拍器,后来被取消了)。
  • 谢谢马特。在我的animationDidStop 委托方法中,我将strokeEnd 设置回1。这是我的代码sn-p:[CATransaction setDisableActions:YES]; self.theLayer.strokeEnd = 1.0; [CATransaction setDisableActions:NO]; 但是,我仍然得到一个闪光,我假设因为一旦动画完成,它会将strokeEnd 重置回来为图层的原始值(即 0),然后将其设置为 1.0。如何去除这种闪光效果?
  • 请按照我说的去做。不在代表中。就在这里,作为您已经展示的代码的一部分。
  • 我修改了答案以向您展示我在说什么。只需在将动画添加到图层的同时将其设置为最终值。
猜你喜欢
  • 1970-01-01
  • 2012-01-12
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
相关资源
最近更新 更多