id | title | brief | sdk | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3DE8385B-075C-3B7F-33D4-9CA048E26DE6 |
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. |
|
To display an image inside a scroll view and support the double-tap to zoom gesture:
-
Add the image to your Xamarin.iOS project and ensure the Build Action is set to BundleResource. The example code loads the image “halloween.jpg”
-
Declare class level fields for a
UIScrollView
andUIImageVIew
UIScrollView scrollView;
UIImageView imageView;
- Create a UIScrollView and it to the View Controller:
scrollView = new UIScrollView (
new CGRect (0, 0, View.Frame.Width
, View.Frame.Height - NavigationController.NavigationBar.Frame.Height));
View.AddSubview (scrollView);
- Create a
UIImageView
and it to the ScrollView:
imageView = new UIImageView (UIImage.FromFile ("halloween.jpg"));
scrollView.ContentSize = imageView.Image.Size;
scrollView.AddSubview (imageView);
- Set the zoom properties:
scrollView.MaximumZoomScale = 3f;
scrollView.MinimumZoomScale = .1f;
scrollView.ViewForZoomingInScrollView += (UIScrollView sv) => { return imageView; };
- Create a
UITapGestureRecognizer
and configure it for two taps, then attach it to the Scroll View:
UITapGestureRecognizer doubletap = new UITapGestureRecognizer(OnDoubleTap) {
NumberOfTapsRequired = 2 // double tap
};
scrollView.AddGestureRecognizer(doubletap); // detect when the scrollView is double-tapped
- Implement the handler to change the zoom level when a double-tap is detected on the Scroll View:
private void OnDoubleTap (UIGestureRecognizer gesture) {
if (scrollView.ZoomScale >= 1)
scrollView.SetZoomScale(0.25f, true);
else
scrollView.SetZoomScale(2f, true);
}
These screenshots show the image zoomed out and zoomed in: