在C#中设置对象的高度和宽度的动画

时间:2012-04-02 20:57:32

标签: c# wpf animation

我试图让这些省略号增长,但我无法弄清楚如何开始动画。这是我第一次尝试WPF动画,我不太明白它是如何工作的。

private void drawEllipseAnimation(double x, double y)
{
    StackPanel myPanel = new StackPanel();
    myPanel.Margin = new Thickness(10);

    Ellipse e = new Ellipse();
    e.Fill = Brushes.Yellow;
    e.Stroke = Brushes.Black;
    e.Height = 0;
    e.Width = 0;
    e.Opacity = .8;
    canvas2.Children.Add(e);
    Canvas.SetLeft(e, x);
    Canvas.SetTop(e, y);

    DoubleAnimation myDoubleAnimation = new DoubleAnimation();
    myDoubleAnimation.From = 0;
    myDoubleAnimation.To = 10;
    myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));
    myStoryboard = new Storyboard();
    myStoryboard.Children.Add(myDoubleAnimation);
    Storyboard.SetTargetName(myDoubleAnimation, e.Name);
    Storyboard.SetTargetProperty(myDoubleAnimation, new     PropertyPath(Ellipse.HeightProperty));
    Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Ellipse.WidthProperty));
}

1 个答案:

答案 0 :(得分:8)

这里不需要故事板。只是做

e.BeginAnimation(Ellipse.WidthProperty, myDoubleAnimation);
e.BeginAnimation(Ellipse.HeightProperty, myDoubleAnimation);

如果您确实需要使用Storyboard,则必须将单独的动画(每个动画属性一个)添加到Storyboard。当您不申请名称时,您必须致电SetTarget而不是SetTargetName。最后,您需要通过调用Begin启动故事板:

DoubleAnimation widthAnimation = new DoubleAnimation
{
    From = 0,
    To = 10,
    Duration = TimeSpan.FromSeconds(5)
};

DoubleAnimation heightAnimation = new DoubleAnimation
{
    From = 0,
    To = 10,
    Duration = TimeSpan.FromSeconds(5)
};

Storyboard.SetTargetProperty(widthAnimation, new PropertyPath(Ellipse.WidthProperty));
Storyboard.SetTarget(widthAnimation, e);

Storyboard.SetTargetProperty(heightAnimation, new PropertyPath(Ellipse.HeightProperty));
Storyboard.SetTarget(heightAnimation, e);

Storyboard s = new Storyboard();
s.Children.Add(widthAnimation);
s.Children.Add(heightAnimation);
s.Begin();