Pages

Sunday, June 3, 2012

WPF Animation (Tower of Hanoi)


A friend of mine implemented well known problem The Tower of Hanoi in WPF.
I think it's a good example of WPF animation, so I decided to share it with you.
Tower Of Hanoi Problem
The Tower of Hanoi Problem
The key of the whole thing is Animate method:

private void Animate(int f, Canvas cn, double x, double y)
{
      Canvas.SetZIndex(cn, Canvas.GetZIndex(cn) * 10);
      DoubleAnimation dax = new DoubleAnimation();
      dax.Duration = new Duration(TimeSpan.FromSeconds(MOVe_SPEED));
      dax.From = cn.RenderTransformOrigin.X;
      dax.To = x;

      DoubleAnimation day = new DoubleAnimation();
      day.Duration = new Duration(TimeSpan.FromSeconds(MOVe_SPEED));
      day.From = cn.RenderTransformOrigin.Y;
      day.To = y;

      TranslateTransform tf = new TranslateTransform();
      cn.RenderTransform = tf;
      tf.SetValue(Canvas.LeftProperty, x);
      tf.SetValue(Canvas.TopProperty, y);
      tf.SetValue(dprop, f);
      tf.SetValue(CanvasProp, cn);

      tf.Changed += new EventHandler(tf_Changed);
      tf.BeginAnimation(TranslateTransform.XProperty, dax);
      tf.BeginAnimation(TranslateTransform.YProperty, day);
}
Please, download the source code here.
Check out another good example of WPF Application which I posted recently - Fifteen Puzzle Game.

No comments:

Post a Comment