在代码后面的WPF中立即翻译动画

时间:2015-03-29 03:10:06

标签: c# wpf animation

我想制作一个动画,其中涉及在x轴上将圆圈_fixedCircle从起点(5,0)转换为终点(200,0)< / strong>然后从(200,0)(5,0) 在永久循环中但不遵循路径,但是“ “跳跃”,换句话说,从点到点立即翻译。

要对此圆进行动画处理,请进行线性插值:

Storyboard sb = new Storyboard();
DoubleAnimation anim = new DoubleAnimation();
sb.Children.Add(anim);
Storyboard.SetTarget(anim, _fixedCircle);
Storyboard.SetTargetProperty(anim, new PropertyPath("(Canvas.Left)"));
anim.From = 5;
anim.To = 200;
anim.RepeatBehavior = RepeatBehavior.Forever;
anim.AutoReverse = true;
MYCANVAS.Resources.Add("CIRCLE_ID", sb);
Duration duration = new Duration(TimeSpan.FromSeconds(2));
anim.Duration = duration;
anim.Begin();   

但是如何创造“跳跃”效应?

3 个答案:

答案 0 :(得分:3)

尝试使用DoubleAnimationUsingKeyFrames,为您想要的每次跳转添加DiscreteDoubleKeyFrame,例如(跳跃值的计算有很大的改进空间;)):

DoubleAnimationUsingKeyFrames anim = new DoubleAnimationUsingKeyFrames();

int maxNrOfJumps = 10;
for (int jump = 0; jump < maxNrOfJumps; jump++) {
    double value = ((200 - 5) / maxNrOfJumps) * jump;
    anim.KeyFrames.Add(new DiscreteDoubleKeyFrame(value, KeyTime.FromPercent(jump / (double)maxNrOfJumps)));
}
  

像DiscreteDoubleKeyFrame这样的离散关键帧会在值之间产生突然的“跳跃”(无插值)。换句话说,动画属性在达到关键帧的关键时间之前不会改变,此时动画属性突然变为目标值。

https://msdn.microsoft.com/en-us/library/system.windows.media.animation.discretedoublekeyframe%28v=vs.110%29.aspx

修改

运行它可以在没有Storyboard的情况下完成,这就是我测试它的方式:

_fixedCircle.BeginAnimation(Canvas.LeftProperty, anim);

编辑2:

您仍然需要设置这些属性以保持动画运行:

anim.RepeatBehavior = RepeatBehavior.Forever;
anim.AutoReverse = true;

另外,不要忘记设置Duration ...

答案 1 :(得分:0)

  

从点到点的即时翻译

您是否正在寻找从第一点到最后一点的即时传送?

如果是这样的话:

Storyboard sb = new Storyboard();
DoubleAnimation anim = new DoubleAnimation();
sb.Children.Add(anim);
Storyboard.SetTarget(anim, _fixedCircle);
Storyboard.SetTargetProperty(anim, new PropertyPath("(Canvas.Left)"));
anim.From = 5;
anim.To = 200;
// anim.RepeatBehavior = RepeatBehavior.Forever; // nope
anim.AutoReverse = false; // well
MYCANVAS.Resources.Add("CIRCLE_ID", sb);
Duration duration = new Duration(TimeSpan.FromSeconds(0)); // here we go
anim.Duration = duration;
anim.Begin();

答案 2 :(得分:0)

为什么不使用skipToFill属性? 只需将其添加到storyboard