Json Json - 3 months ago 112
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:

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

<ScrollViewer Grid.Row="2"
Name="scroll"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">

<Canvas Name="Container"
ClipToBounds="True"
MouseWheel="Container_MouseWheel"
>

<Image Name="ImageSource"
>
<Image.LayoutTransform>
<MatrixTransform/>
</Image.LayoutTransform>
</Image>
</Canvas>
</ScrollViewer>
</Grid>


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

Replace

transform.Matrix = matrix;

with

element.RenderTransform = new MatrixTransform( matrix );

and it works ;)

Comments