tags:

views:

146

answers:

2

I've Image placed inside a ScrollViewer.

<ScrollViewer x:Name="imageScroller" Grid.Column="2" Margin="5" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible">
    <Image x:Name="imageViewer" Cursor="Hand" RenderTransformOrigin="0,0" Margin="0">
        <Image.LayoutTransform>
            <ScaleTransform ScaleX="{Binding Path=Zoom, Converter={StaticResource debugConverter}}" ScaleY="{Binding Path=Zoom, Converter={StaticResource debugConverter}}"/>
        </Image.LayoutTransform>
    </Image>
</ScrollViewer>

How do I zoom image like "fit-to-width" in document viewers to the size and height of ScrollViewer?

A: 

ScrollViewer is not right choice for this. It gives all available space for its child unless you disable scrolling. To stretch images, we usually use Stretch="Fill" property, but, again, it will not work with ScrollViewer.

<ScrollViewer x:Name="imageScroller" Margin="5" 
              HorizontalScrollBarVisibility="Disabled" 
              VerticalScrollBarVisibility="Disabled">
    <Image x:Name="imageViewer" Cursor="Hand" RenderTransformOrigin="0,0" Margin="0" 
           Stretch="Fill"/>
</ScrollViewer>

This approach will work for stretching image, but it disables scrolling.

Anvaka
A: 

I'm doing this by setting the scale for the ScaleTransform in a event handler for the ScrollViewer Load event. Basically I divide the ActualWidth of the ScrollViewer by the width of the source of the image. I also have a handler for the ScrollViewer SizeChanged event that will recalulate the scale so that the image will shrink and grow if you resize your window. Here's some basic code.

Note: This does not take the vertical scrollbar into account, in fact a search on how to handle that is how I ended up here. I'll update when I find an answer for that.

private void imageScroller_Loaded(object sender, RoutedEventArgs e)
{
    FitToWidth();
}

private void imageScroller_SizeChanged(object sender, SizeChangedEventArgs e)
{
    if(imageScroller.IsLoaded)
        FitToWidth();
}

private void FitToWidth()
{
    scaler.ScaleX = scaler.ScaleY = imageScroller.ActualWidth / imageViewer.Source.Width;
}
juharr