Scale, Pan, Rotate Gestures in Xamarin IOS

xamarin

How about if you need to scale, pan and rotate gesture to an image in your native IOS application. GestureRecognizer is used to introduce gesture in your application. Basic three of the gestures which we are going to discuss,

  • RotationGestureRecognizer
  • PinchGestureRecognizer
  • PanGestureRecognizer

Lets take an example of a UIImage in our case and apply all these gestures to that Image.

RotationGestureRecognizer:

  1. rotateGesture = new UIRotationGestureRecognizer((() =>  
  2.   {  
  3.   if ((rotateGesture.State == UIGestureRecognizerState.Began || rotateGesture.State == UIGestureRecognizerState.Changed) && (rotateGesture.NumberOfTouches == 2))   
       {  
  4.       imageView.Transform = CGAffineTransform.MakeRotation(rotateGesture.Rotation + r);  
  5.     }  
  6.       else if (rotateGesture.State == UIGestureRecognizerState.Ended)   
  7.      {  
  8.        r += rotateGesture.Rotation;  
  9.       }  
  10.   }));  
PinchGestureRecognizer:
  1. pinchGesture = new UIPinchGestureRecognizer(() =>   
  2.   {  
  3.   if (pinchGesture.State == UIGestureRecognizerState.Began || pinchGesture.State == UIGestureRecognizerState.Changed)   
  4.     {  
  5.         pinchGesture.View.Transform *= CGAffineTransform.MakeScale(pinchGesture.Scale, pinchGesture.Scale);  
  6.         pinchGesture.Scale = 1;  
  7.     }  
  8.   });  
PanGestureRecognizer:
  1. panGesture = new UIPanGestureRecognizer(() =>   
  2.      {  
  3.     if ((panGesture.State == UIGestureRecognizerState.Began || panGesture.State == UIGestureRecognizerState.Changed) && (panGesture.NumberOfTouches == 1))   
  4.       
  5.        {  
  6.          var p0 = panGesture.LocationInView(View);    
  7.         if (dx == 0)  
  8.             dx = p0.X - imageView.Center.X;    
  9.         if (dy == 0)  
  10.             dy = p0.Y - imageView.Center.Y;  
  11.         var p1 = new PointF(p0.X - dx, p0.Y - dy);  
  12.         imageView.Center = p1;  
  13.       }  
  14.       else if (panGesture.State == UIGestureRecognizerState.Ended)   
  15.       {  
  16.         dx = 0;  
  17.         dy = 0;  
  18.       }  
  19.     });    
Adding Gesture to UIImage:
  1. panGesture.MaximumNumberOfTouches = 2;  
  2. imageView.AddGestureRecognizer(panGesture);  
  3. imageView.AddGestureRecognizer(rotateGesture);  
  4. imageView.AddGestureRecognizer(pinchGesture);