Json Json - 1 year ago 495
C# Question

Zoom on image according to mouse position in wpf

I have some issue to zoom on an image which is in a canvas. I was thinking about using matrixtransform but it doesn't work. It returns me an exception that I don't understand! Here is the XAML:

<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
<Button Click="Button_Click"/>

<ScrollViewer Grid.Row="2"

<Canvas Name="Container"

<Image Name="ImageSource"

The code behind:

private void Button_Click(object sender, RoutedEventArgs e)
Bitmap Bmp = new Bitmap(@"C:\Desktop\image1.bmp");
ImageSource.Source = CreateBitmapSourceFromGdiBitmap(Bmp);
Container.Width = Bmp.Width;
Container.Height = Bmp.Height;

private void Container_MouseWheel(object sender, MouseWheelEventArgs e)
var element = sender as UIElement;
var position = e.GetPosition(element);
var transform = element.RenderTransform as MatrixTransform;
var matrix = transform.Matrix;
var scale = e.Delta >= 0 ? 1.1 : (1.0 / 1.1); // choose appropriate scaling factor

matrix.ScaleAtPrepend(scale, scale, position.X, position.Y);
transform.Matrix = matrix;

If someone could give me a hint that would be nice, thanks!

Answer Source


transform.Matrix = matrix;


element.RenderTransform = new MatrixTransform( matrix );

and it works ;)