Android
iOS
 

Implement Tap-to-Zoom

This recipe shows how to load an image into a scroll view and allow the user to double-tap to zoom.

Recipe

To display an image inside a scroll view and support the double-tap to zoom gesture:

1. Add the image to your Xamarin.iOS project and ensure the Build Action is set to Content. The example code loads the image “halloween.jpg”

2. Declare class level fields for a UIScrollView and UIImageVIew

UIScrollView scrollView;
UIImageView imageView;

3. Create a UIScrollView and it to the View Controller:

scrollView = new UIScrollView (
new RectangleF (0, 0, View.Frame.Width
, View.Frame.Height - NavigationController.NavigationBar.Frame.Height));
View.AddSubview (scrollView);

4. Create a UIImageView and it to the Scroll View:

imageView = new UIImageView (UIImage.FromFile ("halloween.jpg"));
scrollView.ContentSize = imageView.Image.Size;
scrollView.AddSubview (imageView);

5. Set the zoom properties:

scrollView.MaximumZoomScale = 3f;
scrollView.MinimumZoomScale = .1f;
scrollView.ViewForZoomingInScrollView += (UIScrollView sv) => { return imageView; };

6. Create a UITapGestureRecognizer and configure it for two taps, then attach it to the Scroll View:

UITapGestureRecognizer doubletap = new UITapGestureRecognizer();
doubletap.NumberOfTapsRequired = 2; // double tap
doubletap.AddTarget (this, new MonoTouch.ObjCRuntime.Selector("DoubleTapSelector"));
scrollView.AddGestureRecognizer(doubletap); // detect when the scrollView is double-tapped

7. Implement the target selector to change the zoom level when a double-tap is detected on the Scroll View:

[MonoTouch.Foundation.Export("DoubleTapSelector")]
public void OnDoubleTap (UIGestureRecognizer sender) {
   if (scrollView.ZoomScale >= 1)
       scrollView.SetZoomScale(0.25f, true);
   else
       scrollView.SetZoomScale(2f, true);
}

These screenshots show the image zoomed out and zoomed in: