4

我正在通过将 StrokeDashOffset 动画应用于 Rectangle 控件来实现“行军蚂蚁”风格的动画。我希望在矩形可见时播放动画,但在隐藏时不占用额外的 CPU 周期。WPF 是否足够智能,可以在隐藏受影响的控件时自动暂停动画?

4

2 回答 2

7

不。WPF 足够聪明,会这样做:)。这背后的原因是动画系统无法对动画属性的作用做出假设(它可以是任何依赖属性,与控件外观无关,在这种情况下,您希望动画无论可见性如何都可以工作)。

您可以按如下方式进行测试:

XAML:

<Window x:Class="WpfApplication1.TestBrowser"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Animation Test"
        Height="300"
        Width="300">
    <StackPanel>
            <Button Content="Toggle label" 
                            Click="ToggleLableClick"/>
            <local:MyLabel x:Name="lbl" Content="Hello" />
    </StackPanel>
</Window>

C#:

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace WpfApplication1
{
  public partial class TestBrowser : Window
  {
    public TestBrowser()
    {
      InitializeComponent();
        var da = new DoubleAnimation(0, 10, new Duration(TimeSpan.FromSeconds(10)))
                    {
                        AutoReverse = true,
                        RepeatBehavior = RepeatBehavior.Forever
                    };
        lbl.BeginAnimation(MyLabel.DoublePropertyProperty, da);
    }

    private void ToggleLableClick(object sender, RoutedEventArgs e)
    {
        lbl.Visibility = lbl.IsVisible ? Visibility.Collapsed : Visibility.Visible;
    }
  }

    public class MyLabel : Label
    {
        public double DoubleProperty
        {
            get { return (double)GetValue(DoublePropertyProperty); }
            set { SetValue(DoublePropertyProperty, value); }
        }

        public static readonly DependencyProperty DoublePropertyProperty =
                DependencyProperty.Register("DoubleProperty", typeof(double), typeof(MyLabel), 
                new FrameworkPropertyMetadata(0.0,
                    FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange, OnDoublePropertyChanged));

        private static void OnDoublePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Trace.WriteLine(e.NewValue);
        }

        protected override Size MeasureOverride(Size constraint)
        {
            Trace.WriteLine("Measure");
            return base.MeasureOverride(constraint);
        }

        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            Trace.WriteLine("Arrange");
            return base.ArrangeOverride(arrangeBounds);
        }
    }
}

您将在调试输出中看到 WPF 出色的证明:它显示DoubleProperty控件是否可见的变化,但在测量/排列时可见性很重要。控件折叠时不会调用处理程序,即使我标记DoubleProperty为影响测量和排列的属性...

于 2010-02-25T12:02:11.383 回答
0

我认为动画还在继续,但渲染系统会意识到矩形是​​不可见的,不会浪费时间重绘任何东西。

可以为 Visibility 或 Opacity 属性设置动画,如果动画系统将可见性考虑在内,这将不起作用。

于 2010-02-25T11:52:09.233 回答