http://blog.csdn.net/chaoyuan899/article/details/14055767
UIRotationGestureRecognizer手势识别器,就像名称一样,这个类能用来监听和捕获旋转的手势,能帮助你创建出更直观的图形用户界面,比如一种场景,当你的应用中有一个展示图片的视图,用户需要通过旋转图片来调整图片的方向。
UIRotationGestureRecognizer这个类有一个rotation的属性,这个属性可以用来设置旋转的方向和旋转的弧度。旋转是从手指的初始位置(UIGestureRecognizerStateBegan)到最终位置(UIGestureRecognizerStateBegan)决定的。
为了对继承自UIView的UI元素进行旋转,你可以将旋转手势识别器的rotation属性传递给CGAffineTransformMakeRotation方法,以制作一个仿射转场
- //
- // ViewController.m
- // 旋转手势
- //
- // Created by Rio.King on 13-11-2.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import "ViewController.h"
- @interface ViewController ()
- @property (nonatomic,strong)UIRotationGestureRecognizer *rotationGestureRecognizer;
- @property (nonatomic,strong)UILabel *helloWorldLabel;
- @property (nonatomic,unsafe_unretained)CGFloat rotationAngleInRadians;
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- self.helloWorldLabel = [[UILabel alloc] initWithFrame:CGRectZero];
- self.helloWorldLabel.text = @"Hello World!";
- self.helloWorldLabel.font = [UIFont systemFontOfSize:16.0f];
- [self.helloWorldLabel sizeToFit];
- self.helloWorldLabel.center = self.view.center;
- [self.view addSubview:self.helloWorldLabel];
- self.rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
- [self.view addGestureRecognizer:self.rotationGestureRecognizer];
- }
- -(void)handleRotation:(UIRotationGestureRecognizer *)paramSender{
- if (self.helloWorldLabel == nil) {
- return ;
- }
- /*take the previous rotation and add the current rotation to it */
- self.helloWorldLabel.transform = CGAffineTransformMakeRotation(self.rotationAngleInRadians
- +paramSender.rotation);
- /*at the end of the rotation, keep the angle for later use*/
- if (paramSender.state == UIGestureRecognizerStateEnded) {
- self.rotationAngleInRadians += paramSender.rotation;
- }
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- @end
在添加完如上代码之后,我们可以根据旋转的手势角度给我们的这个标签设置一个旋转的角度,但是你可能会遇到如下问题,当一个旋转的动作结束了,另外的一个旋转动作又开始了,第二个旋转的手势角度将会把我们第一次的旋转手势角度给替换掉,因此在第一个旋转动作没有发生的时候,第二个旋转的角度就把第一个旋转的角度覆盖掉。所以我们需要无论这个旋转的手势动作什么时候结束,我们都必须要让当前的这次旋转动作进行下去,因此我们就需要添加一个旋转角度的队列,让我们的标签按照这个队列中的旋转角度依次的进行旋转运动。
我们在上面提到一个CGAffineTransformMakeRotation的方法,这个方法可用来创建依序变化的队列。注意,在iOS SDK中所有以"CG"开都的都需要引入,CoreGraphice框架包。
运行效果如下: