WPF Animate width and Height with code behind (Zoo

2019-08-12 09:56发布

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);
    }

2条回答
爷、活的狠高调
2楼-- · 2019-08-12 10:16

It is better to use scale transform for zooming, but if you insist on animating W/H you can do it, since these are normal DP you can animate them using standard DoubleAnimation/DoubleAnimationUsingKeyFrames Something like

DoubleAnimation doubleAnimation = new DoubleAnimation(100, 200, new Duration(TimeSpan.FromMilliseconds(500)));
        this.BeginAnimation(FrameworkElement.WidthProperty, doubleAnimation);
查看更多
女痞
3楼-- · 2019-08-12 10:22

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);

    }
查看更多
登录 后发表回答