KnowDotNet

Create a Gradient background on your Forms or Controls

by William Ryan

These days Moore's Law is more alive than ever.  As such, developers are paying a lot more attention to the 'User Experience'.  There are companies like Infragistics and Component One who's sole product lines involve UI enhancing tools.

Ok, so let's say you want to use a common technique that's pretty popular these days, the Gradient.  It's a LOT easier than you might think.  (Combine this with the techniques I mention in my Opacity article, and you can really get cool.  Anyway, it's a lot easier than you might think.  The code is pretty self explanatory:

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
Dim BaseRectangle As New Rectangle(0, 0, Me.Width - 1, Me.Height - 1)
'You can use whatever colours you want, I just chose Orange and Green so that
'because they are the colors of my Beloved Hurricanes
'Anyway, all that's happening is that I  declare a rectangle to match the surface
'area of the form (BaseRectangle), pick Two Colors, and then select an Angle for your gradient.
'Yes, pretty simple, but after all, isn't that what .NET is supposed to be about?
Dim Gradient_Brush As New LinearGradientBrush(BaseRectangle, Color.Orange, Color.Green, 45)
  e.Graphics.FillRectangle(Gradient_Brush, BaseRectangle)
End Sub


Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Resize
        
Me.Invalidate()
End Sub


This last line is really important though.  If you don't invalidate the existing image and the form is resized, you'll see the smaller image appear to be  superimposed on your newly sized form. Trust me, it's tacky.  Also, another cool but little known feature of Invalidate is that you can pass in a Rectangle if you want, thereby causing only part of the Form to be invalidate.  It's certainly not something you run across every day, but it's a cool feature when you need it.  For kicks, I include an example below:

  Me.Invalidate(New Rectangle(0, 0, 100, 100))

To really get a feel for how invalidate works, I'd encourage you to first leave it out and then run the program maximizing and minimizing your form.  You'll see the superimposition.  Then, add the code in the Resize event and see what happens then.  Finally, add the Invalidate overload and see what happens.

I fought learning GDI+ for a while, but it's quickly becomming one of my favorite features of .NET because it gives you the ability to make things really nice for your users.  Gradients are without a doubt one of my favorites.

Enjoy!