使用CGAffineTransformRotate进行ios旋转动画

时间:2014-04-01 10:25:46

标签: ios animation

我想要执行一些旋转动画。现在我这样做:

#define degreesToRadians(x) (M_PI * x / 180.0)

[self.crossButton setTransform:CGAffineTransformRotate(self.crossButton.transform, degreesToRadians(-rotationDegree))];

但是当我通过例如360度时,不会发生。当我将值传递到180以上时,它开始不会很好地运转。你知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

你的问题是' setTransformation'适用于矩阵旋转。因此,您将始终获得最终结果的最短路径。当您传递360度旋转时,您的对象在转换后将是相同的。出于这个原因,转换将无所作为,因为它已经在它应该结束的地方。对于180到360度之间的值,您的旋转将再次向后旋转。轮换使用最短的'最终结果的路径。

您可以尝试以下代码:

UIView* toRotate = VIEW_TO_ROTATE;
CGFloat degreesToRotate = DEGREES;
CGFloat animationTime = TOTAL_ANIMATION_TIME;


NSInteger intervals = ((int)degreesToRotate)/179.9;
CGFloat rest = degreesToRotate-(intervals*179.9);

CGFloat radInterval = degreesToRotate>=0?179.9:-179.9;
CGFloat radRest = (M_PI * rest / 180.0);

CGFloat intervalTime = (1-(radRest/M_PI/2))/intervals;
CGFloat restTime = (radRest/M_PI/2)/intervals;

[UIView animateKeyframesWithDuration:animationTime
                               delay:0.0f
                             options:UIViewKeyframeAnimationOptionCalculationModeLinear
                          animations:
 ^{
     for (int i=0; i<intervals; i++) {
         [UIView addKeyframeWithRelativeStartTime:intervalTime*i relativeDuration:intervalTime animations:^{
             toRotate.transform = CGAffineTransformConcat(toRotate.transform, CGAffineTransformMakeRotation(radInterval));
         }];
     }
     [UIView addKeyframeWithRelativeStartTime:intervalTime*intervals relativeDuration:restTime animations:^{
         toRotate.transform = CGAffineTransformConcat(toRotate.transform, CGAffineTransformMakeRotation(radRest));
     }];
 } completion:^(BOOL finished) {

 }];

请务必将VIEW_TO_ROTATEDEGREESTOTAL_ANIMATION_TIME替换为您需要的值!