I want to create a zooming control, that can be operated with mouse wheel.
Scroll up -> zoom in; scroll down -> zoom out.
Additionally, I want the zoom center to be located at wherever the mouse pointer is. So that one can always zoom in on the spot, where the mouse cursor is.
Seems simple enough, yet I can't get to work.
I am using a Grid
and applying ScaleTransform
to it.
When I zoom in the first time, it works and zooms in that particular spot. But then, if I move the cursor to some other spot and try to zoom in a bit more, the Grid
is being offset and my initial center is off.
What is causing this? How can fix this?
My code:
Class MainWindow
Dim trans As New ScaleTransform
Dim Scale As Double = 1
Private Sub DefGrid_MouseWheel(sender As Object, e As MouseWheelEventArgs) Handles DefGrid.MouseWheel
If e.Delta > 0 Then
Scale = Scale + 0.1
End If
If e.Delta < 0 Then
Scale = Scale - 0.1
End If
trans.CenterX = e.GetPosition(DefGrid).X
trans.CenterY = e.GetPosition(DefGrid).Y
trans.ScaleX = Scale
trans.ScaleY = Scale
DefGrid.RenderTransform = trans
End Sub
End Class
And the xaml:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" PreviewMouseWheel="Window_PreviewMouseWheel">
<Grid x:Name="DefGrid" HorizontalAlignment="Left" Height="291" Margin="19,10,0,0" VerticalAlignment="Top" Width="475">
<Canvas HorizontalAlignment="Left" Height="254" Margin="137,10,0,0" VerticalAlignment="Top" Width="195">
<Canvas.Background>
<ImageBrush ImageSource="TestImage.jpg"/>
</Canvas.Background>
</Canvas>
</Grid>
</Window>
There's a Canvas image on the grid, just for reference.