Animate a Color in WPF

WPF lets you do some amazing things.  One is the fact that even simple things like a Brush can be animated.  This lets you do some very smooth looking color transitions between one color to the next.  You can even animate the alpha channel to modify the opacity of the brush and basically make objects fade in or fade out easily.

Here is a handy function I use when animating brushes in the code behind:

public static Brush GetAnimatedBrush(Color fromColor, Color toColor, TimeSpan ts)
	ColorAnimationUsingKeyFrames ani = new ColorAnimationUsingKeyFrames();

	LinearColorKeyFrame f1 = new LinearColorKeyFrame(fromColor)
		{KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 200))};

	EasingColorKeyFrame f2 = new EasingColorKeyFrame(toColor) {KeyTime = KeyTime.FromTimeSpan(ts)};


	SolidColorBrush brush = new SolidColorBrush(Color.FromArgb(0, 75, 75, 75));

	brush.BeginAnimation(SolidColorBrush.ColorProperty, ani);

	return brush;

To use this function you just need to give it a color to start from, a color to end with and the time you want the transition between the two colors to take. It will give you back a brush that has started the animation so just assign the brush to your objects Background or something and your set.

Categories:   Code

Tags:  , ,