A simple was how to draw a gradient on a form. All you need is to include both Drawing and Drawing2D namespaces in your project. As we are going to draw onto the form, we need to assure, that if user resizes it, we will have our gradient spread over the whole form. We can do this by using form’s Resize event. Each time the form is being resized, we tell it to repaint.
1 2 3 4 |
private void Form1_Resize(object sender, EventArgs e) { this.Invalidate(); } |
In order to paint on the form, we are going to use its Paint event. In this way, the next time a message to repaint is received, we will have our gradient repainted.
The class LinearGradientBrush creates a special brush, which we can use in our further work. It accepts four arguments:
- a rectangle, which determines the area where we are going to paint
- color one
- color two
- an angle
Here is a simple example.
1 2 3 4 5 6 7 8 9 |
private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.Clip = new Region(ClientRectangle); LinearGradientBrush gradient = new LinearGradientBrush(ClientRectangle, Color.Peru, Color.Pink, 90f); e.Graphics.SmoothingMode = SmoothingMode.HighQuality; // set the quality e.Graphics.FillRectangle(gradient, ClientRectangle); gradient.Dispose(); } |