C
C#10mo ago
SilverBrother

WPF Image Zoom fixed to absolute window position and not relative mouseposition

- The title explains the issue briefly. So I'm making a simple App with WPF where I want to be able to zoom in and out on images. When I zoom in on the first mouse position it does as intended, but if I move the mouse to a different position it is like the program assumes that it is zooming in on the mouse position related to the original unzoomed image, instead of the position on the zoomed image. I.e. I have a Europe map and first step I zoom in on Berlin without moving the mouse, second step, I now want to zoom in on a street in the south western Berlin, but instead the App zooms (pans) down to Spain due to the cursor's position in the original image. I hope it makes sense. I don't think there are issues in the WPF, but I'm missing something in the C# file. Here it is
C#
public partial class MainWindow : Window
{
private double zoomScale = 1.0;

public MainWindow()
{
InitializeComponent();
}
private void ZoomedImage_MouseWheel(object sender, MouseWheelEventArgs e)
{
// Get the mouse position relative to the image
Point mousePos = e.GetPosition(imagemap);

// Adjust the zoom scale based on the mouse wheel delta
double delta = e.Delta > 0 ? 0.1 : -0.1;
zoomScale += delta;

// Constrain the zoom scale within reasonable limits
zoomScale = Math.Max(1.0, Math.Min(zoomScale, 10.0));

// Apply the zoom scale using a ScaleTransform
ScaleTransform scaleTransform = new ScaleTransform(zoomScale, zoomScale);

// Set the center of the ScaleTransform to the mouse position
scaleTransform.CenterX = mousePos.X;
scaleTransform.CenterY = mousePos.Y;

imagemap.RenderTransform = scaleTransform;

e.Handled = true; // Prevent scrolling
}
}
C#
public partial class MainWindow : Window
{
private double zoomScale = 1.0;

public MainWindow()
{
InitializeComponent();
}
private void ZoomedImage_MouseWheel(object sender, MouseWheelEventArgs e)
{
// Get the mouse position relative to the image
Point mousePos = e.GetPosition(imagemap);

// Adjust the zoom scale based on the mouse wheel delta
double delta = e.Delta > 0 ? 0.1 : -0.1;
zoomScale += delta;

// Constrain the zoom scale within reasonable limits
zoomScale = Math.Max(1.0, Math.Min(zoomScale, 10.0));

// Apply the zoom scale using a ScaleTransform
ScaleTransform scaleTransform = new ScaleTransform(zoomScale, zoomScale);

// Set the center of the ScaleTransform to the mouse position
scaleTransform.CenterX = mousePos.X;
scaleTransform.CenterY = mousePos.Y;

imagemap.RenderTransform = scaleTransform;

e.Handled = true; // Prevent scrolling
}
}
1 Reply
lycian
lycian10mo ago
Point mousePos = e.GetPosition(imagemap);
This is probably the problem. I'm going to guess GetPosition doesn't account for the render transform. I'm not sure what the right answer is but I'd either look at translating that point into the render space, or setting the RenderTransformOrigin
Want results from more Discord servers?
Add your server