Gradient is a method which consists in slowly switching from one color to another - it’s used very often in application’s design.

In this tutorial I’ll show you how to create this effect using only code:

First, create a Forms Project, then add the following line:

1
using System.Drawing.Drawing2D;


Now, we’ll create a Rectangle as big as our window and add the gradient effect to it.

1
Rectangle gradient_rectangle = new Rectangle(0, 0, Width, Height);


Then using the LinearGradientBrush we add the two main colors. Everything else is done by .NET. Really simple, isn’t it?
To assign the gradient effect to the Rectangle, use the following code:

1
2
graphics.FillRectangle(brush, gradient_rectangle);  //graphics comes from a PaintEventArgs argument(event)


As you can see, the LinearGradientBrush takes 4 arguments:

• the first is the rectangle we made before
• the second and the third are the Colors that will create the gradient - we start from Black and we get to Blue
• the fourth is the gradient’s angle (float), I set it to 45 degrees here.

Finally, we can create a simple function to do everything needed:

1
2
3
4
5
6
7
8
9
10
11
12
13
private void set_background(Object sender, PaintEventArgs e)
{
Graphics graphics = e.Graphics;

//the rectangle, the same size as our Form
Rectangle gradient_rectangle = new Rectangle(0, 0, Width, Height);

Brush b = new LinearGradientBrush(gradient_rectangle, Color.FromArgb(0, 0, 0), Color.FromArgb(57, 128, 227), 65f);


1