https://img-mid.csdnimg.cn/release/static/image/mid/ask/731918728856166.png "#left")
把上图的小球理解为火车,path为火车道,我需要根据现实火车的移动实时更新小球的位置。
已经绘制好了火车道的路径,非实时显示也已经实现,参考资料:https://www.cnblogs.com/zhouyinhui/archive/2007/07/31/837893.html ; https://blog.csdn.net/weixin_33805557/article/details/89591090
现在我需要根据火车的位置实时显示动画,即火车在第一车道走了10米,我也要在界面上的第一车道行走10米,火车停我也要停。火车道非直线车道,是弯曲的。
寻求思路:现在需要用wpf实现实时显示火车运行动画
已经获取火车位置(相对起始点移动距离)、速度、方向(前进或后退);
位置转化
private void DrawScale()
{
double majorTickUnitValue = this.ScaleSweepLenth / this.MajorDivisionsCount;
double minorTickUnitValue = this.ScaleSweepLenth / this.MinorDivisionsCount;
double correctionOffset = this.rootGrid.Width / 2 ;
Double minvalue = MinValue; ;
//画主刻度
for (int i = 0; i < this.MajorDivisionsCount; i++)
{
Rectangle majorTickRect = new Rectangle();
majorTickRect.Height = this.MajorTickSize.Height;
majorTickRect.Width = this.MajorTickSize.Width;
majorTickRect.Fill = new SolidColorBrush(this.MajorTickColor);
TransformGroup majorTickTransformGroup = new TransformGroup();
TranslateTransform majorTickTranslateTransform = new TranslateTransform();
majorTickTranslateTransform.X = i * majorTickUnitValue - correctionOffset;
majorTickTranslateTransform.Y = this.MajorMinorDivisionOffset;
majorTickTransformGroup.Children.Add(majorTickTranslateTransform);
majorTickRect.RenderTransform = majorTickTransformGroup;
this.rootGrid.Children.Add(majorTickRect);
}
}
动画
private void MovePointerUsingAnimate(double oldValue, double newValue)
{
if (null != this.pointer)
{
double distanceOldAndNew = Math.Abs(newValue - oldValue);
DoubleAnimation doubleAnimation = new DoubleAnimation();
double animDuration = 0.0f;
Storyboard movingPointerStoryboard = new Storyboard();
TransformGroup transformGroup = new TransformGroup();
TranslateTransform transform = new TranslateTransform();
doubleAnimation.From = oldValue;
doubleAnimation.To = newValue;
animDuration = distanceOldAndNew * animatingSpeedFactor;
doubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(animDuration));
movingPointerStoryboard.Completed +=new EventHandler(MovingPointerStoryboardStoryboard_Completed);
movingPointerStoryboard.Children.Add(doubleAnimation);
Storyboard.SetTarget(doubleAnimation, this.pointer);
transformGroup.Children.Add(transform);
this.pointer.RenderTransform = transformGroup;
Storyboard.SetTargetProperty(doubleAnimation,
new PropertyPath("(Path.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)"));
if (Math.Abs(oldValue - newValue) > 0)
{
movingPointerStoryboard.Begin();
}
}
}
MVVM 双向绑定二者的位置数值,后台修改后会自动同步体现到小球的位置