Search code examples
iphoneobjective-ccore-animation

rotate a UIImageView 360 degrees using block-based


How can I rotate an UIImageView 360 degrees using BLOCK-BASED animation?

here is my try, but it repeat 180 rotations instead of two consecutive animations

   void (^anim) (void) = ^{
         uiImgDisc.transform = CGAffineTransformMakeRotation(3.14159265);
    };

    void (^after) (BOOL) = ^(BOOL f){
        [UIView animateWithDuration:1
                              delay:0
                            options:UIViewAnimationCurveLinear
                         animations:^(void){
                             uiImgDisc.transform = CGAffineTransformMakeRotation(3.14159265);
                         }
                         completion:nil];

    };

    [UIView animateWithDuration:1
                          delay:0
                        options:UIViewAnimationCurveLinear | UIViewAnimationOptionRepeat
                     animations:anim
                     completion:after];

Solution

  • It isn't block based, but you might want to try using CAKeyFrameAnimation where you specify a few key frames that the animation needs to incorporate. The benefit versus the block based method is that the Core Animation method will allow more fluid animations.

    It may be a little overkill, because as Rob says, you can just do a CABasicAnimation and set the fromValue and toValue to 0 and 2*M_PI, respectively. But this example shows you how you could also do arbitrary rotation animations with fluid motion.

    First, make sure you add the QuartzCore Framework to your build phases. Then make sure you import the header using

    #import <QuartzCore/QuartzCore.h> 
    

    then in your rotation method, do this:

    CAKeyframeAnimation *theAnimation = [CAKeyframeAnimation animation];
    theAnimation.values = [NSArray arrayWithObjects:
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(0, 0,0,1)],
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(3.13, 0,0,1)],
                           [NSValue valueWithCATransform3D:CATransform3DMakeRotation(6.26, 0,0,1)],
                           nil];
    theAnimation.cumulative = YES;
    theAnimation.duration = 1.0;
    theAnimation.repeatCount = 0;
    theAnimation.removedOnCompletion = YES;
    
    
    theAnimation.timingFunctions = [NSArray arrayWithObjects:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn], 
                                    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut],
                                    nil
                                    ];
    
    [imageView.layer addAnimation:theAnimation forKey:@"transform"];
    

    inspired by the following: https://github.com/jonasschnelli/UIView-i7Rotate360

    Good Luck!

    t