【发布时间】:2014-03-20 03:59:00
【问题描述】:
我正在尝试通过代码而不是 XAML 在窗口中的 WPF 中学习一些东西。我希望有更多的时间线来同时变换对象(矩形)。我的意思是 RotateTransform 和 TransitionTransform 由一个命令调用。
Rectangle aRectangle = new Rectangle();
aRectangle.Width = 30;
aRectangle.Height = 30;
aRectangle.Fill = Brushes.Blue;
TransformGroup g = new TransformGroup();
RotateTransform rotateTransform = new RotateTransform();
TranslateTransform animatedTranslateTransform = new TranslateTransform();
g.Children.Add(rotateTransform);
g.Children.Add(animatedTranslateTransform);
aRectangle.RenderTransformOrigin = new Point(0.5, 0.5);
aRectangle.RenderTransform = g;
PathGeometry animationPath = new PathGeometry();
PathFigure pFigure = new PathFigure();
pFigure.StartPoint = new Point(0, 0);
seg.Points.Add(new Point(0, 100));
seg.Points.Add(new Point(100, 100));
seg.Points.Add(new Point(100, 50));
seg.Points.Add(new Point(50, 50));
pFigure.Segments.Add(seg);
animationPath.Figures.Add(pFigure);
animationPath.Freeze();
DoubleAnimationUsingPath translateXAnimation =
new DoubleAnimationUsingPath();
translateXAnimation.PathGeometry = animationPath;
translateXAnimation.Duration = TimeSpan.FromSeconds(5);
translateXAnimation.Source = PathAnimationSource.X;
DoubleAnimationUsingPath translateYAnimation =
new DoubleAnimationUsingPath();
translateYAnimation.PathGeometry = animationPath;
translateYAnimation.Duration = TimeSpan.FromSeconds(5);
translateYAnimation.Source = PathAnimationSource.Y;
DoubleAnimation translateAngle = new DoubleAnimation(0, 360, new Duration(TimeSpan.FromSeconds(5)));
如果我使用此代码一切正常:
rotateTransform.BeginAnimation(RotateTransform.AngleProperty, translateAngle);
animatedTranslateTransform.BeginAnimation(TranslateTransform.XProperty, translateXAnimation);
animatedTranslateTransform.BeginAnimation(TranslateTransform.YProperty, translateYAnimation);
但这似乎很复杂,我试图了解如何将所有动画一起运行。我已经尝试过 Storyboard,但我必须使用 Canvas.Left 和 Top 来移动它,而且旋转也不起作用。
【问题讨论】:
-
强烈建议不要在 WPF 的过程代码中创建或操作 UI 元素。你真的应该学习 XAML。
-
@HighCore - 总的来说我同意,但是当您需要根据数据大量自定义动画时,编写 C# 代码而不是在 XAML 中进行大量绑定可能更容易。
-
@ErnodeWeerd 现在不是 OP 的情况。在 WPF 中避免 XAML 就像在 C# 中避免 LINQ。
-
@HighCore - 虽然题外话:当我需要速度时我会避免使用 Linq,但通常我会使用它。他的问题很明确:他想知道如何在 XAML 中做到这一点。
-
ParallelTimeline 是您想要的吗?