下面介绍的是缩放手势和捏合手势:
直接上代码:
1 #import "ViewController.h" 2 3 @interface ViewController ()<UIGestureRecognizerDelegate> 4 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad { 10 [super viewDidLoad]; 11 // Do any additional setup after loading the view, typically from a nib. 12 13 //如果需要同时旋转和缩放我们还需要实现一个协议UIGestureRecognizerDelegate 14 15 16 UIImage *image = [UIImage imageNamed:@"2.jpg"]; 17 18 UIImageView *imageView = [[UIImageView alloc]init]; 19 imageView.frame = CGRectMake(100, 200, 300, 400); 20 imageView.userInteractionEnabled = YES; 21 imageView.image = image; 22 [self.view addSubview:imageView]; 23 24 //添加缩放手势(捏合手势) 25 _pinGes = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinchAct:)]; 26 27 [imageView addGestureRecognizer:_pinGes]; 28 29 //创建旋转手势 30 _rotGes = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(RotGes:)]; 31 32 [imageView addGestureRecognizer:_rotGes]; 33 34 //设置协议代理 35 _pinGes.delegate = self; 36 _rotGes.delegate = self; 37 38 } 39 40 - (void)pinchAct:(UIPinchGestureRecognizer *)pin{ 41 //获取监控图像视图(也就是上面的imageView对象) 42 UIImageView *Iview = (UIImageView *)pin.view; 43 //对图像视图对象进行矩阵变换计算并赋值 44 // transform 表示图形的变换 45 //CGAffineTransformScale 通过缩放的方式产生一个新矩阵 46 //p1 原来的矩阵 47 //p2 x方向的的缩放比例 48 //p3 y方向的缩放比例 49 Iview.transform = CGAffineTransformScale(Iview.transform, pin.scale, pin.scale); 50 51 52 //将缩放值归位为单位值 53 pin.scale = 1; 54 55 } 56 57 - (void)RotGes:(UIRotationGestureRecognizer *)rotGes{ 58 59 //获取旋转对象 60 UIImageView *Iview = (UIImageView *)rotGes.view; 61 //计算旋转变化并赋值 62 Iview.transform = CGAffineTransformRotate(Iview.transform, rotGes.rotation); 63 64 //选择角度清零; 65 rotGes.rotation = 0; 66 67 68 } 69 //实现协议方法 70 //是否可以同时响应俩个手势 71 //如果返回值为YES 可以同时响应; 72 -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ 73 74 return YES; 75 }
这样就可以简单的实现对视图的缩放(捏合)和旋转.
时间: 2024-11-19 08:42:41