ios开发--旋转、移动、缩放手势实例代码

时间:2021-12-15 12:04:21

代码如下:

  1. // 添加所有的手势
  2. - (void) addGestureRecognizerToView:(UIView *)view
  3. {
  4. // 旋转手势
  5. UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotateView:)];
  6. [view addGestureRecognizer:rotationGestureRecognizer];
  7. // 缩放手势
  8. UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchView:)];
  9. [view addGestureRecognizer:pinchGestureRecognizer];
  10. // 移动手势
  11. UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)];
  12. [view addGestureRecognizer:panGestureRecognizer];
  13. }
  14. // 处理旋转手势
  15. - (void) rotateView:(UIRotationGestureRecognizer *)rotationGestureRecognizer
  16. {
  17. UIView *view = rotationGestureRecognizer.view;
  18. if (rotationGestureRecognizer.state == UIGestureRecognizerStateBegan || rotationGestureRecognizer.state == UIGestureRecognizerStateChanged) {
  19. view.transform = CGAffineTransformRotate(view.transform, rotationGestureRecognizer.rotation);
  20. [rotationGestureRecognizer setRotation:0];
  21. }
  22. }
  23. // 处理缩放手势
  24. - (void) pinchView:(UIPinchGestureRecognizer *)pinchGestureRecognizer
  25. {
  26. UIView *view = pinchGestureRecognizer.view;
  27. if (pinchGestureRecognizer.state == UIGestureRecognizerStateBegan || pinchGestureRecognizer.state == UIGestureRecognizerStateChanged) {
  28. view.transform = CGAffineTransformScale(view.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
  29. pinchGestureRecognizer.scale = 1;
  30. }
  31. }
  32. // 处理拖拉手势
  33. - (void) panView:(UIPanGestureRecognizer *)panGestureRecognizer
  34. {
  35. UIView *view = panGestureRecognizer.view;
  36. if (panGestureRecognizer.state == UIGestureRecognizerStateBegan || panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
  37. CGPoint translation = [panGestureRecognizer translationInView:view.superview];
  38. [view setCenter:(CGPoint){view.center.x + translation.x, view.center.y + translation.y}];
  39. [panGestureRecognizer setTranslation:CGPointZero inView:view.superview];
  40. }
  41. }

别忘了

  1. [self addGestureRecognizerToView:view];

如果处理的是图片,别忘了

  1. [imageView setUserInteractionEnabled:YES];
  2. [imageView setMultipleTouchEnabled:YES];