Search code examples
c#winformsgradientbrush

(...) doesn't exist in the current context - Gradient and others brushes


I saw a way to make a form's background color Gradient.

That was done by a GradientBrush but when I try that, it says it doesn't exist.

I wrote like this:

GradientBrush something = New GradientBrush();

In the output window I see the "doesn't exist in the current context" error.


Solution

  • In a winforms Form you could do this:

    using  System.Drawing.Drawing2D;
    ...
    ...
    
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        using (LinearGradientBrush br = new
                LinearGradientBrush(Form1.ClientRectangle, Color.Wheat, Color.DimGray, 0f))
            e.Graphics.FillRectangle(br, Form1.ClientRectangle);
    }
    

    To get rid of flicker set the form to DoubleBuffered = true;

    For more colors use the multicolor overload of the LinearGradientBrush! For an example see here!

    enter image description here

    If the background is fixed you may consider creating a Bitmap with the gradient. Perfect if the user will not resize the form..:

    Bitmap form1Back = new Bitmap(form1.ClientSize.Width, form1.ClientSize.Height);
    using (Graphics G = Graphics.FromImage(form1Back))
    using (LinearGradientBrush br = new 
           LinearGradientBrush( form2.ClientRectangle, Color.Wheat, Color.DimGray, 0f))
        G.FillRectangle(br, form2.ClientRectangle);
    form1.BackgroundImage = form1Back;