C# LinearGradientBrush. How can I change the point where the two colors blend?

1.7k views Asked by At

I have this code that allows me to add some blending to my windows form:

public partial class Form1 : Form
{
    protected override void OnPaintBackground(PaintEventArgs e)
    {
        using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle, 
               Color.White, 
               Color.Black, 
               LinearGradientMode.Vertical))
        {
            e.Graphics.FillRectangle(brush, this.ClientRectangle);
        }
    }
}

And this is the result:

enter image description here

By default, the "peak" of the blending of the two colors is right in the middle of the box. I want to adjust the code in such way that the "peak" of the blending occurs about 3/4 towards the top. Is it possible to change the point where the two colors start to blend?

Thank you in advance.

1

There are 1 answers

1
Reza Aghaei On BEST ANSWER

You can set InterpolationColors property of the brush to a suitable ColorBlend for example:

using (var brush = new LinearGradientBrush(this.ClientRectangle,
    Color.Transparent, Color.Transparent, LinearGradientMode.Vertical))
{
    var blend = new ColorBlend();
    blend.Positions = new[] { 0, 3 / 4f, 1 };
    blend.Colors = new[] { Color.White, Color.Black, Color.Black };
    brush.InterpolationColors = blend;
    e.Graphics.FillRectangle(brush, this.ClientRectangle);
}

enter image description here

Or for example another blend:

blend.Positions = new[] { 0, 1 / 2f, 1 };
blend.Colors = new[] { Color.White, Color.Gray, Color.Black };

enter image description here