开发者

Changing the Zoom In/Out centerpoint

I'm writing a WPF application that displays a XAML object (it's basically a map drawn in XAML). As part of its features, it should zoom in/out and pan. The panning works fine, and the zoom zooms, but I can't quite understand how to zoom to a specific point, like my mouse cursor, for example.

This is my current code:

internal void PerformZoom(float ZoomFactor, Point ZoomCenterPoint)
{
  m_originalTransform = m_canvas.RenderTransform;
  float newZoomFactor = m_oldZoomFactor + ZoomFactor;

  float scaleToApply = (newZoomFactor / m_oldZoomFactor);
  m_totalZoom = newZoomFactor;

  var st = new ScaleTransform(scaleToApply, scaleToApply);

  TransformGroup tg = new TransformGroup();
  tg.Children.Add(m_originalTransform);
  tg.Children.Add(st);
  m_canvas.RenderTransform = tg;

  m_oldZoomFactor = newZoomFactor;
}

[edit] Found the solution - Just edited the CenterX / Center开发者_JAVA技巧Y properties of the transformation and it worked like a charm. Thanks for all your help!

[edit2] Here's a viable solution (considering the mouse position):

public partial class MainWindow
{
    private float currentZoom = 1f;
    private const float StepSize = .2f;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void MainGrid_OnMouseWheel(object sender, MouseWheelEventArgs e)
    {
        var pos = 1;
        if (e.Delta < 0)
        {
            pos = -1;
        }

        var mousePosition = e.MouseDevice.GetPosition(MainGrid);

        currentZoom += StepSize * pos;
        var transform = new ScaleTransform(currentZoom, currentZoom, mousePosition.X, mousePosition.Y);
        MainGrid.RenderTransform = transform;
    }
}


You will have to compose your ScaleTransform with a TranslateTransform which translates your component while zooming.

The offset given by the TranslateTransform depends of the behavior you wanna have (i.e. center on mouse, center on screens center...)

I wrote in the past a behavior which you can attach to a component : It makes it zoomable (centered on mouse, reacting to mousewheel) It's pretty dirty and not sure to be efficient (i no longer use it)... and comments are in french :-/

see the source

[edit] In fact, I remember it was to scroll and scale a Panels background. But it shouldnt be so hard to modify for applying it to any object as the transformations are the same for images and elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜