Question

I'm spinning continuously an UIImageView using CABasicAnimation and I want to be able to get the rotation angle.

-(void)viewDidAppear:(BOOL)animated{

    [self spinAnimationOnView:self.myImageView
                        duration:2
                          repeat:HUGE_VAL];
}

- (void)spinAnimationOnView:(UIView*)view duration:(CGFloat)duration repeat:(float)repeat{
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0];
    rotationAnimation.duration = duration;
    rotationAnimation.repeatCount = repeat;

    [view.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}

The animation behaves as expected. But then I try to get the rotation angle like this:

CGFloat angle = [(NSNumber *)[self.myImageView valueForKeyPath:@"layer.transform.rotation.z"] floatValue];

NSLog(@"ROTATION = %f", angle);

And the output is always 0. Any thoughts?

Was it helpful?

Solution

While an animation is in progress, you need to use the CALayer's presentationLayer to get the state of the layer. See the CALayer docs.

CGFloat angle = [[self.myImageView valueForKeyPath:@"layer.presentationLayer.transform.rotation.z"] floatValue];

NSLog(@"ROTATION = %f", angle);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top