在后面的代码中在WPF中创建一个Blink动画

时间:2014-05-11 09:45:48

标签: c# wpf animation blink

我想将Blink动画应用于Canvas,以便我在其上绘制的所有对象都会闪烁。

我使用下面的代码有点成功,它会更快地更改Opacity的{​​{1}}属性以达到此效果,但我对此并不满意。

我希望在当前代码中没有任何Canvas的纯闪烁。我怎么能以正确的方式做到这一点?

FadeOut/FadeIn

也许我可以使用var blinkAnimation = new DoubleAnimation { From = 1, To = 0 }; var blinkStoryboard = new Storyboard { Duration = TimeSpan.FromMilliseconds(500), RepeatBehavior = RepeatBehavior.Forever, AutoReverse = true }; Storyboard.SetTarget(blinkAnimation, MyCanvas); Storyboard.SetTargetProperty(blinkAnimation, new PropertyPath(OpacityProperty)); blinkStoryboard.Children.Add(blinkAnimation); MyCanvas.BeginStoryboard(blinkStoryboard); 来做到这一点,但我无法做到。

2 个答案:

答案 0 :(得分:7)

您可以使用具有适当BeginTime的第二个动画:

var switchOffAnimation = new DoubleAnimation
{
    To = 0,
    Duration = TimeSpan.Zero
};

var switchOnAnimation = new DoubleAnimation
{
    To = 1,
    Duration = TimeSpan.Zero,
    BeginTime = TimeSpan.FromSeconds(0.5)
};

var blinkStoryboard = new Storyboard
{
    Duration = TimeSpan.FromSeconds(1),
    RepeatBehavior = RepeatBehavior.Forever
};

Storyboard.SetTarget(switchOffAnimation, MyCanvas);
Storyboard.SetTargetProperty(switchOffAnimation, new PropertyPath(Canvas.OpacityProperty));
blinkStoryboard.Children.Add(switchOffAnimation);

Storyboard.SetTarget(switchOnAnimation, MyCanvas);
Storyboard.SetTargetProperty(switchOnAnimation, new PropertyPath(Canvas.OpacityProperty));
blinkStoryboard.Children.Add(switchOnAnimation);

MyCanvas.BeginStoryboard(blinkStoryboard);

答案 1 :(得分:1)

如果您想要动画的开/关状态,可以将动画更改为DoubleAnimationUsingKeyFrames

var blinkAnimation = new DoubleAnimationUsingKeyFrames();
blinkAnimation.KeyFrames.Add(new DiscreteDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(0))));
blinkAnimation.KeyFrames.Add(new DiscreteDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(250))));

var blinkStoryboard = new Storyboard
{
    Duration = TimeSpan.FromMilliseconds(500),
    RepeatBehavior = RepeatBehavior.Forever,
};

Storyboard.SetTarget(blinkAnimation, MyCanvas);
Storyboard.SetTargetProperty(blinkAnimation, new PropertyPath(OpacityProperty));

blinkStoryboard.Children.Add(blinkAnimation);
blinkStoryboard.Begin();