Search code examples
c#wpfanimationcode-behind

WPF Animate width and Height with code behind (Zoom in)


I am able to animate the movement of a Border:

private void MoveTo(Border target, double newX, double newY)
{
    Vector offset = VisualTreeHelper.GetOffset(target);
    var top = offset.Y;
    var left = offset.X;
    TranslateTransform trans = new TranslateTransform();
    target.RenderTransform = trans;
    DoubleAnimation anim1 = new DoubleAnimation(0, newY - top, TimeSpan.FromMilliseconds(500));
    DoubleAnimation anim2 = new DoubleAnimation(0, newX - left, TimeSpan.FromMilliseconds(500));
    trans.BeginAnimation(TranslateTransform.YProperty, anim1);
    trans.BeginAnimation(TranslateTransform.XProperty, anim2);
}

But I would like to be able to animate an increase in Height and Width as well as position to give the impression of enlarging an image(which is contained in a Border in my case and example above)).

Is this spossible with code behind?


OK, I tried the scale transform but it does not appear to do anything - do I need a storyboard?

    private void Zoom(Border target)
    {   
        TranslateTransform trans = new TranslateTransform();
        target.RenderTransform = trans;
        DoubleAnimation anim1 = new DoubleAnimation(1, 2, TimeSpan.FromMilliseconds(1000));
        DoubleAnimation anim2 = new DoubleAnimation(1, 2, TimeSpan.FromMilliseconds(1000));
        trans.BeginAnimation(ScaleTransform.ScaleXProperty, anim1);
        trans.BeginAnimation(ScaleTransform.ScaleYProperty, anim2);
    }

Solution

  • Use ScaleTransform, no need for Height & Width animations, the ScaleTransform will affect your Border's VisualTree so the inner image will be stretched as well.

        private void Zoom(Border target)
        {
            ScaleTransform trans = new ScaleTransform();
            target.RenderTransform = trans;
            // if you use the same animation for X & Y you don't need anim1, anim2 
            DoubleAnimation anim = new DoubleAnimation(1, 2, TimeSpan.FromMilliseconds(1000));
            trans.BeginAnimation(ScaleTransform.ScaleXProperty, anim);
            trans.BeginAnimation(ScaleTransform.ScaleYProperty, anim);
    
        }