在WPF中创建一个闪烁动画

本文关键字:一个 闪烁 动画 WPF 创建 | 更新日期: 2023-09-27 18:02:41

我想把Blink的动画应用到Canvas上,这样我在它上面画的所有对象都会跟着它闪烁。

我已经成功地使用下面的代码,改变CanvasOpacity属性相当快地实现这种效果,但我有点不满意。

我更喜欢没有任何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);

也许我可以使用VisibilityProperty,但我不能得到正确的

在WPF中创建一个闪烁动画

您可以使用第二个动画与适当的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);

如果你想要你的动画的开/关状态,你可以改变你的动画为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();