Zoom Out Image to fit ScrollViewer Dimensions

2019-02-15 15:07发布

问题:

I have a little issue with zooming accordingly an image. I have an Image in my XAML, with a ScrollViewer attached so it can be zoomed. Like this :

<ScrollViewer x:Name="ImageScrollViewer">
    <Image x:Name="ImagePanel" 
           Stretch="Uniform" 
           VerticalAlignment="Center" 
           HorizontalAlignment="Center"/>
</ScrollViewer>

What I'd like to do is that, in case the image is too big to fit the image control and needs to be zoomed out (only in this case), I'd like to programatically set the ZoomFactor of the ScrollViewer so it fits the Image control. My problem is, I don't really know how could I determine that factor, considering my image's width and height.

Also I'd like not to scale the picture, to change it in any way, I'd seen some similar topics on SO for this issue but so far, none have applied to my case. I just need to zoom out my picture until there's no vertical/horizontal scrollbars visible.

Any suggestions on how to do this, are greatly appreciated, thank you!

回答1:

You can set the dimensions (Width, Height) of the Image to match the ScrollViewer.ViewportWidth/Height, so that by default all of the image is visible. Then set MinZoomFactor to 1 so that no-one zooms out beyond what makes sense and MaxZoomFactor to something that would make sense.

If you want more control - leave the Image size properties on the default Auto (and VerticalAlignment/HorizontalAlignment different than Stretch), compare aspect ratios of the ScrollViewer (ViewportWidth/ViewportHeight) to the Image (ActualWidth/ActualHeight assuming Image.Stretch="None" and that the Image is actually loaded). If the ScrollViewer aspect ratio is wider - the MinZoomFactor you will want will be ScrollViewer.ViewportHeight / Image.ActualHeight. If the Image aspect ratio is wider - the MinZoomFactor you will want will be ScrollViewer.ViewportWidth / Image.ActualWidth. MaxZoomFactor should be 1 regardless unless you want to zoom to more than screen pixel per image pixel (at 100% scaling of the application).

You might find my blog post interesting:

http://blog.onedevjob.com/2012/07/21/creating-a-zoomable-scrollviewer-with-zoomsnappoints-in-winrt-xaml/