Posted by: Zeeshan Amjad | December 11, 2009

Gradient Animation with Code


We can create very interesting effect with the combination of gradient and animation. In this example we are going to study the linear gradient with change the offset position of the color with animation. For simplicity we create this effect completely with code, so we don’t have to use the story board class. We set the background color of window, but the same technique can be used with any other controls.

Here is a complete code of this program.

  1: using System;
  2: using System.Windows;
  3: using System.Windows.Controls;
  4: using System.Windows.Media;
  5: using System.Windows.Media.Animation;
  6: 
  7: public class MyWindow : Window
  8: {
  9:     public MyWindow()
 10:     {
 11:         Title = "Animation";
 12:         Width = 300;
 13:         Height = 300;
 14: 
 15:         LinearGradientBrush lgb = new LinearGradientBrush();
 16:         GradientStop gs1 = new GradientStop(Colors.Blue, 0);
 17:         GradientStop gs2 = new GradientStop(Colors.White, 0);
 18:         GradientStop gs3 = new GradientStop(Colors.Blue, 1);
 19:         lgb.GradientStops.Add(gs1);
 20:         lgb.GradientStops.Add(gs2);
 21:         lgb.GradientStops.Add(gs3);
 22: 
 23:         Background = lgb;
 24: 
 25:         DoubleAnimation da = new DoubleAnimation();
 26:         da.From = 0;
 27:         da.To = 1;
 28:         da.AutoReverse = true;
 29:         da.RepeatBehavior = RepeatBehavior.Forever;
 30:         da.Duration = TimeSpan.FromSeconds(1);
 31:         gs2.BeginAnimation(GradientStop.OffsetProperty, da);
 32:     }
 33: }
 34: 
 35: public class AnimationClass
 36: {
 37:     [STAThread]
 38:     public static void Main()
 39:     {
 40:         MyWindow win = new MyWindow();
 41:         Application app = new Application();
 42:         app.Run(win);
 43:     }
 44: }

These are the output of the program.

GradientAnimation_01

GradientAnimation_02

Advertisements

Responses

  1. Good Example for Gradient colors.

    • Thanks to like it.
      Regards
      Zeeshan Amjad


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: