【问题标题】:.NET WPF Window FadeIn and FadeOut Animation.NET WPF 窗口淡入和淡出动画
【发布时间】:2011-04-15 14:01:43
【问题描述】:

下面是窗口淡入淡出动画的代码sn-ps:

// Create the fade in storyboard
fadeInStoryboard = new Storyboard();
fadeInStoryboard.Completed += new EventHandler(fadeInStoryboard_Completed);
DoubleAnimation fadeInAnimation = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(0.30)));
Storyboard.SetTarget(fadeInAnimation, this);
Storyboard.SetTargetProperty(fadeInAnimation, new PropertyPath(UIElement.OpacityProperty));
fadeInStoryboard.Children.Add(fadeInAnimation);

// Create the fade out storyboard
fadeOutStoryboard = new Storyboard();
fadeOutStoryboard.Completed += new EventHandler(fadeOutStoryboard_Completed);
DoubleAnimation fadeOutAnimation = new DoubleAnimation(1.0, 0.0, new Duration(TimeSpan.FromSeconds(0.30)));
Storyboard.SetTarget(fadeOutAnimation, this);
Storyboard.SetTargetProperty(fadeOutAnimation, new PropertyPath(UIElement.OpacityProperty));
fadeOutStoryboard.Children.Add(fadeOutAnimation);

以下是触发动画的辅助方法:

/// <summary>
/// Fades the window in.
/// </summary>
public void FadeIn()
{
   // Begin fade in animation
   this.Dispatcher.BeginInvoke(new Action(fadeInStoryboard.Begin), DispatcherPriority.Render, null);
}

/// <summary>
/// Fades the window out.
/// </summary>
public void FadeOut()
{
   // Begin fade out animation
   this.Dispatcher.BeginInvoke(new Action(fadeOutStoryboard.Begin), DispatcherPriority.Render, null);
}

代码运行良好,除了两个问题:

  1. 在 FadeIn() 上,窗口以难看的黑色背景开始,然后正确设置动画。
  2. 在 FadeOut() 正确设置动画后,窗口以难看的黑色背景结束。

为什么会这样?如何让这个动画顺利运行而不会出现黑色背景?

【问题讨论】:

    标签: .net wpf animation window


    【解决方案1】:

    您需要在 Window 上将 AllowsTransparency 设置为 true 以使其完全透明。

    不幸的是,这只能通过WindowStyle=None 实现,因此您必须实现自己的标题栏。

    这带来了一些令人讨厌的性能问题,因为窗口不能再被硬件渲染。如果您采用这种方式,我强烈建议您在 UI 线程上将 RenderOptions.ProcessRenderMode 设置为 RenderMode.SoftwareOnly(.NET 4.0 或更高版本),以便在简单合成中获得可接受的性能。

    【讨论】:

    • 您好,多苏先生。感谢您的回答。我使用自定义的 WPF 窗口,因此已经设置了 WindowStyle=None 属性。将设置 RenderOptions.SoftwareOnly 以提高性能。我在 VS 2010 .NET 4.0 :)
    • 分层窗口(WindowStyle=None、AllowsTransparency=True、Background=Transparent)可以在 Windows Vista 或更高版本上进行硬件渲染。
    猜你喜欢
    • 1970-01-01
    • 2011-10-26
    • 2014-01-20
    • 2012-12-18
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多