CABasicAnimation如何获得当前的旋转角度

时间:2012-04-08 10:44:24

标签: ios xcode4 rotation caanimation cabasicanimation

我对CABasicAnimation有一些问题。它类似于帖子:CABasicAnimation rotate returns to original position

所以,我的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;
}

此动画工作正常,但如果我在animationRotation结束前调用touchBegan,则旋转角度为beginValue。我需要阴极电流旋转角度。作为实验,我声明了方法

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

它看起来很有效。但我不知道如何在animationDidStop中为我的UIImageView获取角度值或CGAffineTransform。 甚至可以做到吗?感谢。

1 个答案:

答案 0 :(得分:9)

你应该使用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;
    }