Friday, 15 July 2011

This post deals with rotating a view with animation with the help of core graphics. Quartz framework provides us with class "CGAffineTransform.h" which contains the function "CGAffineTransform CGAffineTransformRotate ( CGAffineTransform t, CGFloat angle );" that takes the current affine transform matrix and angle in radians as parameters, and returns the resultant affine transform. We will also animate the rotation instead of simply rotating the view by some angle.

Now lets see how it is done.

Suppose we have a view controller class called RotationViewController.

Write the following code in RotationViewController.h" file


#import <UIKit/UIKit.h>

@interface RotationViewController : UIViewController {
 UIImageView *needleview;
 }

@end

Here needleview is the view we are going to rotate.

Now come to RotationViewController.m file and write the following code


- (void)viewDidLoad {
 needleview=[[UIImageView alloc]
initWithImage:[UIImage imageNamed:@"finalneedle.png"]];
 needleview.frame=CGRectMake(100, 100, 36, 221);
 [self.view addSubview:needleview];
    [super viewDidLoad];
}

-(void)viewDidAppear:(BOOL)animated
{
 [UIView animateWithDuration:2.0

  delay: 0.0

 options: UIViewAnimationOptionCurveEaseIn

 animations:^{

 needleview.transform=CGAffineTransformRotate
(needleview.transform, (((60*22)/7)/180));

  }
  completion:nil];

}

In the above code "finalneedle.png" is the image file, in the resources folder, to be used in ImageView. We have implemented "viewDidAppear" to perform rotation with animation after the view appears on screen. The animation block inside the method contains various parameter which has to be set before animating the rotation. The angle of rotation is 60 degree which is converted to radians.

No comments:

Post a Comment