Search code examples
c#wpfimagemovepanning

Image movement like Google Maps


I have an big image which I need to show in a smaller container (or smthg like this). The user should be able to move the image up, down, left & right. It should be like Google Maps.

Do you have an idea where I can start and how to solve this?


Solution

  • Maybe something like DeepZoom would work.


    You could also create a simple UserControl or CustomControl with panning functionality, e.g. have a canvas which handles some mouse events to manipulate a TranslateTransform on your image which should be a child of the canvas.

    Event handling outline:

    // Add this transform to the image as RenderTransform
    private TranslateTransform _translateT = new TranslateTransform();
    private Point _lastMousePos = new Point();
    
    private void This_MouseDown(object sender, MouseButtonEventArgs 
    {
        if (e.ChangedButton == PanningMouseButton)
        {
            this.Cursor = Cursors.ScrollAll;
            _lastMousePos = e.GetPosition(null);
            this.CaptureMouse();
        }
    }
    
    private void This_MouseUp(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == PanningMouseButton)
        {
            this.ReleaseMouseCapture();
            this.Cursor = Cursors.Arrow;
        }
    }
    
    private void This_MouseMove(object sender, MouseEventArgs e)
    {
        if (this.IsMouseCaptured)
        {
            Point newMousePos = e.GetPosition(null);
            Vector shift = newMousePos - _lastMousePos;
            _translateT.X += shift.X;
            _translateT.Y += shift.Y;
            _lastMousePos = newMousePos;
        }
    }