Skip to content

Instantly share code, notes, and snippets.

@DmitriyKirakosyan
Last active March 5, 2023 04:44
Show Gist options
  • Save DmitriyKirakosyan/c6b212f36b9c038a9d32d66eeaeedddc to your computer and use it in GitHub Desktop.
Save DmitriyKirakosyan/c6b212f36b9c038a9d32d66eeaeedddc to your computer and use it in GitHub Desktop.
Improved pinch zoom for ScaleAspectFit images
// This code is a Xamarin adaptation of https://letcreateanapp.com/2021/05/20/pinch-to-zoom-image-in-out-programmatically/
public ImageViewer()
{
scrollView = new UIScrollView
{
ShowsHorizontalScrollIndicator = false,
ShowsVerticalScrollIndicator = false,
BouncesZoom = false,
MinimumZoomScale = 1,
MaximumZoomScale = 4,
};
scrollView.ViewForZoomingInScrollView = _ => imageView;
scrollView.AddGestureRecognizer(new UITapGestureRecognizer(() =>
{
scrollView.SetZoomScale(
scrollView.ZoomScale > scrollView.MinimumZoomScale
? scrollView.MinimumZoomScale
: scrollView.MaximumZoomScale,
true);
})
{
NumberOfTapsRequired = 2,
});
scrollView.DidZoom += ScrollViewDidZoom;
}
public void ScrollViewDidZoom(object s, EventArgs e)
{
if (scrollView.ZoomScale > 1)
{
if (imageView.Image != null)
{
var ratioW = imageView.Frame.Width / imageView.Image.Size.Width;
var ratioH = imageView.Frame.Height / imageView.Image.Size.Height;
var ratio = ratioW < ratioH ? ratioW : ratioH;
var newWidth = imageView.Image.Size.Width * ratio;
var newHeight = imageView.Image.Size.Height * ratio;
var conditionLeft = newWidth * scrollView.ZoomScale > imageView.Frame.Width;
var left = 0.5 * (conditionLeft ? newWidth - imageView.Frame.Width : (scrollView.Frame.Width - scrollView.ContentSize.Width));
var conditionTop = newHeight * scrollView.ZoomScale > imageView.Frame.Height;
var top = 0.5 * (conditionTop ? newHeight - imageView.Frame.Height : (scrollView.Frame.Height - scrollView.ContentSize.Height));
scrollView.ContentInset = new UIEdgeInsets((nfloat)top, (nfloat)left, (nfloat)top, (nfloat)left);
}
}
else
{
scrollView.ContentInset = UIEdgeInsets.Zero;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment