WPF动画宽度和高度,后面有代码(放大)

时间:2012-09-23 11:09:58

标签: c# wpf animation code-behind

我可以为边框的移动制作动画:

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

但我希望能够设置高度和宽度的增加动画以及放置图像的位置(在我的情况和上面的示例中包含在边框中)。)

这背后有代码吗?


好的,我尝试过缩放转换,但似乎没有做任何事情 - 我需要一个故事板吗?

    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 个答案:

答案 0 :(得分:8)

最好使用缩放变换进行缩放,但如果您坚持使用W / H动画,则可以执行此操作,因为这些是普通DP,您可以使用标准DoubleAnimation / DoubleAnimationUsingKeyFrames为它们设置动画。 像

这样的东西
DoubleAnimation doubleAnimation = new DoubleAnimation(100, 200, new Duration(TimeSpan.FromMilliseconds(500)));
        this.BeginAnimation(FrameworkElement.WidthProperty, doubleAnimation);

答案 1 :(得分:0)

使用ScaleTransform,无需Height& Width动画,ScaleTransform会影响您的边框VisualTree,因此内部图像也会被拉伸。

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

    }