Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF zoom canvas and maintain scroll position

Tags:

scroll

canvas

wpf

I have a Canvas element, contained within a ScrollViewer, which I'm zooming using ScaleTransform. However, I want to be able to keep the scroll position of the viewer focused on the same part of the canvas after the zoom operation has finished. Currently when I zoom the canvas the scroll position of the viewer stays where it was and the place the user was viewing is lost.

I'm still learning WPF, and I've been going backwards and forwards a bit on this, but I can't figure out a nice XAML based way to accomplish what I want. Any help in this matter would be greatly appreciated and would aid me in my learning process.

Here is the kind of code I'm using...

<Grid>
    <ScrollViewer Name="TrackScrollViewer" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <Canvas Width="2560" Height="2560" Name="TrackCanvas">
            <Canvas.LayoutTransform>
                <ScaleTransform ScaleX="{Binding ElementName=ZoomSlider, Path=Value}" 
                                ScaleY="{Binding ElementName=ZoomSlider, Path=Value}"/>
            </Canvas.LayoutTransform>

            <!-- Some complex geometry describing a motor racing circuit -->

        </Canvas>
    </ScrollViewer>
    <StackPanel Orientation="Horizontal" Margin="8" VerticalAlignment="Top" HorizontalAlignment="Left">
        <Slider Name="ZoomSlider" Width="80" Minimum="0.1" Maximum="10" Value="1"/>
        <TextBlock Margin="4,0,0,0" VerticalAlignment="Center" Text="{Binding ElementName=ZoomSlider, Path=Value, StringFormat=F1}"/>
    </StackPanel>
</Grid>
like image 365
Alex McBride Avatar asked Mar 14 '10 17:03

Alex McBride


1 Answers

This is not a purely XAML way of doing it, but there is a very nice piece of work on Joeyw's blog titled Pan and Zoom (DeepZoom style) in WPF with links to the source. He has taken some inspiration from DeepZoom and it gives you smooth/animated panning and zooming of content. And if you're using WPF 4 you could probably modify it a little to add some easing functions to the animations to give it an even nicer feel.

like image 153
Andrew Bienert Avatar answered Sep 30 '22 07:09

Andrew Bienert