CABasicAnimation如何获取当前旋转角度

8

我在CABasicAnimation方面遇到了一些问题。这与这篇文章类似:CABasicAnimation旋转返回原始位置

所以,我有一个UIImageView,可以在touchMove中旋转。在touchEnd中调用一个方法来执行“惯性动画”:

-(void)animationRotation: (float)beginValue
{
     CABasicAnimation *anim;
     anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
     anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
     anim.duration = 0.5;
     anim.repeatCount = 1;

     anim.fillMode = kCAFillModeForwards;
     anim.fromValue = [NSNumber numberWithFloat:beginValue];
     [anim setDelegate:self];    

     anim.toValue = [NSNumber numberWithFloat:(360*M_PI/180 + beginValue)];
     [appleView.layer addAnimation:anim forKey:@"transform"];

     CGAffineTransform rot = CGAffineTransformMakeRotation(360*M_PI/180 + beginValue);
     appleView.transform = rot;
}

这个动画本来是正常工作的,但如果我在动画旋转结束之前调用touchBegan,旋转角度就会回到初始值。我需要获取当前旋转角度。为了进行实验,我声明了一个方法。

 -(vod) animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
 {
      NSLog(@"Animation finished!");
 }

看起来似乎工作正常。但我不知道如何获取我的UIImageView在animationDidStop中的旋转角度值或CGAffineTransform值。这是可行的吗?谢谢。

1个回答

10

你应该使用 presentationLayer 方法在动画进行时获取层属性。

因此,你的代码应该像这样:

 #define RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) / (float)M_PI * 180.0f)

    -(void)animationRotation: (float)beginValue
    {
         CABasicAnimation *anim;
         anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
         anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
         anim.duration = 0.5;
         anim.repeatCount = 1;

         anim.fillMode = kCAFillModeForwards;
         anim.fromValue = [NSNumber numberWithFloat:beginValue];
         [anim setDelegate:self];    



    //get current layer angle during animation in flight
         CALayer *currentLayer = (CALayer *)[appleView.layer presentationLayer];     
         float currentAngle = [(NSNumber *)[currentLayer valueForKeyPath:@"transform.rotation.z"] floatValue];   
         currentAngle = roundf(RADIANS_TO_DEGREES(currentAngle));        

         NSLog(@"current angle: %f",currentAngle);



         anim.toValue = [NSNumber numberWithFloat:(360*M_PI/180 + beginValue)];
         [appleView.layer addAnimation:anim forKey:@"transform"];

         CGAffineTransform rot = CGAffineTransformMakeRotation(360*M_PI/180 + beginValue);
         appleView.transform = rot;
    }

谢谢,我试过了,它可以工作,但不完全符合我的预期。我使用了NSTimer动画..但还是谢谢 :-) - frankWhite
点赞该获取当前图层可见旋转角度的方法。 - geraldWilliam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接