2013-04-01 190 views
0

我使用iOS核心动画“CABasicAnimation”为UIImageView设置动画,所有工作都适合我,但唯一的问题是当完成动画后动画到位置回到原来的位置。我怎么能克服这个?我需要保持UIImageView移动位置。iOS“CABasicAnimation”在动画完成后将组件移动到原始位置

注:我已经看到了几个有关这方面的成功答案的问题,但我不知道为什么我的工作不像他们说的那样工作。

After rotating a CALayer using CABasicAnimation the layer jumps back to it's unrotated position

这里是我的示例代码,

CGPoint endPt = CGPointMake(160, 53); 
    CABasicAnimation *anim5 = [CABasicAnimation animationWithKeyPath:@"position"]; 
    [anim5 setBeginTime:CACurrentMediaTime()+0.4]; 
    anim5.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; 
    anim5.fromValue = [NSValue valueWithCGPoint:imgRef.layer.position]; 
    anim5.toValue = [NSValue valueWithCGPoint:endPt]; 
    anim5.duration = 1.5; 
    anim5.speed = 2; 
    [imgRef.layer addAnimation:anim5 forKey:@"position"]; 

    //this is what other answers ask to do 
    [anim5 setFillMode:kCAFillModeForwards]; 
    [anim5 setRemovedOnCompletion:NO]; 

BTW [imgRef.layer setPosition:CGPointMake(160, 53)];不会帮我,因为我推迟动画与4毫秒。

回答

3

其根本原因是动画只是在两个值之间转换属性,它实际上并没有改变结束值。动画完成时需要更改结束值,有三种方法可以实现。 1)使用CAAnimation超类的委托属性通知动画何时完成。此时您可以将属性设置为最终值。请参阅:https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CAAnimation_class/Introduction/Introduction.html#//apple_ref/occ/cl/CAAnimation animationDidStop:finished:是您需要在委托上实现的方法。 2)在周围的CATransaction上设置完成块。您需要手动启动CATransaction,而不是让CABasicAnimation为您自动执行。请参阅:Objective-C - CABasicAnimation applying changes after animation? 3)见OMZ的评论如下...

+1

有一个更好的(更简单)的方法:http://oleb.net/blog/2012/11/prevent-caanimation-snap-back/ – omz

+0

谢谢,omz,你的解决方案修复我的问题 –

+0

我也谢谢! – skinsfan00atg

1

正确的答案是,设置图层的位置属性,但如你所指出的,这使得它更困难,因为你想0.4秒的延迟在职位变更之前。是否有任何理由不能先执行延迟,然后再进行动画制作?类似这样的:

- (IBAction)didTapMove:(id)sender 
{ 
    [self performSelector:@selector(animate) withObject:nil afterDelay:0.4]; 
} 

- (void)animate 
{ 
    CGPoint endPt = CGPointMake(160, 53); 
    CABasicAnimation *anim5 = [CABasicAnimation animationWithKeyPath:@"position"]; 
    anim5.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; 
    anim5.fromValue = [NSValue valueWithCGPoint:_imageView.layer.position]; 
    anim5.toValue = [NSValue valueWithCGPoint:endPt]; 
    anim5.duration = 1.5; 
    anim5.speed = 2; 

    [_imageView.layer addAnimation:anim5 forKey:@"position"]; 

    [_imageView.layer setPosition:CGPointMake(160, 53)]; 
} 

注意我已经从动画中删除了开始时间,因为在执行选择器调用中发生延迟。

+0

谢谢@Matt,你的回答是正确的,但这不是我想要的。这个答案不适合我的情况,因为我有很多动画在一起,所以我真的需要从“CABasicAnimation”延迟。 –

相关问题