Search code examples
c#wpfzoomingtransformscale

Implement a zoom as in Expression Blend


In Expression Blend, when you scroll the mouse wheel, the on-screen elements are zoomed in/out, focused on the position where the mouse is.

I'm trying to implement an identical zoom in my own project, however I'm having problems with it jumping around after zooming, moving the mouse and then zooming again.

So far I'm using a RenderTransform with a ScaleTransform, using the mouse co-ordinates as the centerX and centerY for the ScaleTransform.

Does anyone know how they've done it in Expression Blend?

This is what I've done so far:

    private void ScrollCanvasMouseWheel(object sender, MouseWheelEventArgs e)
    {
        double zoomAmnt = e.Delta > 0 ? 0.2 : -0.2;
        _scaleTransformAmount += zoomAmnt;

        if (_scaleTransformAmount < 0.5)
            _scaleTransformAmount = 0.5;

        Point position = e.GetPosition(ScrollCanvas);

        var scaleTransform = ScrollCanvas.RenderTransform as ScaleTransform;
        if (scaleTransform == null) throw new ArgumentNullException("scaleTransform");

        scaleTransform.ScaleX = _scaleTransformAmount;
        scaleTransform.ScaleY = _scaleTransformAmount;
        scaleTransform.CenterX = position.X;
        scaleTransform.CenterY = position.Y;
    }

Solution

  • That kind of zoom is nice so i tried to implement it once, the maths of it are a bit weird, it took me about two days to figure something out that worked, this might be rather ugly code though (variables with _ are fields on the zoom control):

    Point cursorPos = e.GetPosition(this);
    Point newCenter = _scaleT.Inverse.Transform(_translateT.Inverse.Transform(cursorPos));
    Point oldCenter = new Point(_scaleT.CenterX, _scaleT.CenterY);
    Vector oldToNewCenter = newCenter - oldCenter;
    _scaleT.CenterX = newCenter.X;
    _scaleT.CenterY = newCenter.Y;
    _translateT.X += oldToNewCenter.X * (_scaleT.ScaleX - 1.0);
    _translateT.Y += oldToNewCenter.Y * (_scaleT.ScaleY - 1.0);
    
    _scalingAnimation.From = _scaleT.ScaleX;
    if (e.Delta > 0)
    {
        _scalingAnimation.To = _scaleT.ScaleX * ZoomScaleChangeFactor;
    }
    else
    {
        _scalingAnimation.To = _scaleT.ScaleX / ZoomScaleChangeFactor;
    }
    _scaleT.BeginAnimation(ScaleTransform.ScaleXProperty, _scalingAnimation);
    _scaleT.BeginAnimation(ScaleTransform.ScaleYProperty, _scalingAnimation);
    
    this.ReleaseMouseCapture();
    

    The order of the transforms is important of course:

    TransformGroup tGroup = new TransformGroup();
    tGroup.Children.Add(_scaleT);
    tGroup.Children.Add(_translateT);