我正在尝试获取动画开始和停止的确切时间。使用AnimationClock开始动画。我尝试听过AnimationClock的CurrentStateInvalidated事件,但是当我检查自调用AnimationClock.Controller.Begin()以来经过的时间时,该时间总是少于动画的持续时间(30-50 ms)。动画似乎立即开始。以下代码示例应对此进行演示。
public partial class AnimationTest : Window {
private Stopwatch _stopwatch;
private AnimationClock _clock;
public ICommand StartCommand => new RelayCommand(Start);
public AnimationTest() {
InitializeComponent();
_stopwatch = new Stopwatch();
var a = CreateAnimation();
_clock = a.CreateClock();
MyRectangle.ApplyAnimationClock(MarginProperty, _clock);
_clock.Controller.Stop();
_clock.CurrentStateInvalidated += AnimationClock_CurrentStateInvalidated;
DataContext = this;
}
private ThicknessAnimationUsingKeyFrames CreateAnimation() {
ThicknessAnimationUsingKeyFrames a = new ThicknessAnimationUsingKeyFrames();
var duration = 0;
var durationPerKeyFrame = 400;
a.KeyFrames.Add(new LinearThicknessKeyFrame(new Thickness(400, 300, 0, 0), TimeSpan.FromMilliseconds(duration += durationPerKeyFrame)));
a.KeyFrames.Add(new LinearThicknessKeyFrame(new Thickness(0, 0, 0, 0), TimeSpan.FromMilliseconds(duration += durationPerKeyFrame)));
a.Duration = TimeSpan.FromMilliseconds(duration);
a.FillBehavior = FillBehavior.Stop;
return a;
}
private void WindowLoaded(object sender, RoutedEventArgs e) {
}
private void Start() {
_clock.Controller.Begin();
_stopwatch.Start();
}
private void AnimationClock_CurrentStateInvalidated(object sender, EventArgs e) {
Clock clock = (Clock) sender;
if (clock.CurrentState == ClockState.Active) {
Console.WriteLine("time since start was called " + _stopwatch.ElapsedMilliseconds + " ms");
_stopwatch.Restart();
}
if (clock.CurrentState == ClockState.Stopped) {
Console.WriteLine("time since animation started " + _stopwatch.ElapsedMilliseconds + " ms");
_stopwatch.Reset();
}
}
}
我认为动画实际上比我指定的持续时间短,动画停止之前会触发CurrentStateInvalidated事件,或者动画开始时存在延迟,这会导致StopWatch.Restart()延迟。我怎么知道呢?
在记录眼动数据和音频时,该动画用作刺激,因此我需要确保在动画开始时就开始眼动仪和音频记录,或者至少知道应该如何调整时间因此可以同步播放。我需要寻找WPF以外的其他动画框架吗?