iOS开发中,除了有关触摸的这组方法来控制用户的手指触控外,还可以用UIGestureRecognize的衍生类来进行判断,方便了开发。
UIGestureRecognize的子类类别有以下几种:
- UITapGestureRecognizer //轻拍识别器
- UIPinchGestureRecognizer //捏合识别器
- UIRotationGestureRecognizer //旋转识别器
- UISwipeGestureRecognizer //扫动识别器
- UIPanGestureRecognizer //拖动识别器
- UILongPressGestureRecognizer //长按识别器
下面的例子我是用UIPinchGestureRecognizer和UIRotationGestureRecognizer通过手势实现图片旋转和缩小放大。
ViewController.m中的代码如下;
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong) UIImageView *imageView;
@property(nonatomic) CGFloat lastRotation;
-(void)changeImageSize:(UIPinchGestureRecognizer *)recognizer;
-(void)rotateImage:(UIRotationGestureRecognizer *)rotateRecognizer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//在view上添加一个ImageView
UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Totoro"]];
image.frame = CGRectMake(0, 0, 128, 128);
self.imageView = image;
self.imageView.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
[self.view addSubview:self.imageView];
//添加捏合手势识别器,changeImageSize:方法实现图片的放大与缩小
UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(changeImageSize:)];
[self.view addGestureRecognizer:pinchRecognizer];
//添加旋转手势识别器,rotateImage:方法实现图片的旋转
UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotateImage:)];
[self.view addGestureRecognizer:rotateRecognizer];
}
-(void)changeImageSize:(UIPinchGestureRecognizer *)recognizer
{
CGRect frame = self.imageView.frame;
//监听两手指滑动的距离,改变imageView的frame
frame.size.width = recognizer.scale*128;
frame.size.height = recognizer.scale*128;
self.imageView.frame = frame;
//保证imageView中心不动
self.imageView.center =CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
}
-(void)rotateImage:(UIRotationGestureRecognizer *)rotateRecognizer
{
//改变imageView的角度,使图片旋转
if ([rotateRecognizer state]==UIGestureRecognizerStateEnded) {
self.lastRotation = 0.0;
return;
}
CGAffineTransform currentTransform = self.imageView.transform;
CGFloat rotation = 0.0 - (self.lastRotation - rotateRecognizer.rotation);
CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform,rotation);
self.imageView.transform = newTransform;
self.lastRotation = rotateRecognizer.rotation;
}
@end
运行代码,实现效果如下: