Drawing A Color Gradient

In VB.NET it's easy to fill a form with a gradient. I made this function that will fill a form with a gradient using the colors specified by 2 Color objects and a LinearGradientMode type. It can be used like this:

Protected Overrides Sub OnPaint(ByVal pe As PaintEventArgs)
    DrawGradient(Color.Blue, Color.Firebrick, Drawing.Drawing2D.LinearGradientMode.Horizontal)
End Sub


The function is:

Private Sub DrawGradient(ByVal color1 As Color, ByVal color2 As Color, ByVal mode As System.Drawing.Drawing2D.LinearGradientMode)
    Dim a As New System.Drawing.Drawing2D.LinearGradientBrush(New RectangleF(0, 0, Me.Width, Me.Height), color1, color2, mode)
    Dim g As Graphics = Me.CreateGraphics
    g.FillRectangle(a, New RectangleF(0, 0, Me.Width, Me.Height))
    g.Dispose()
End Sub


You can render text using a similiar method:

Private Sub DrawGradientString(ByVal text as String, ByVal color1 As Color, ByVal color2 As Color, ByVal mode As System.Drawing.Drawing2D.LinearGradientMode)
    Dim a As New System.Drawing.Drawing2D.LinearGradientBrush(New RectangleF(0, 0, 100, 19), color1, color2, mode)
    Dim g As Graphics = Me.CreateGraphics
    Dim f As Font
    f = New Font("arial", 20, FontStyle.Bold, GraphicsUnit.Pixel)
    g.DrawString(text, f, a, 0, 0)
    g.Dispose()
End Sub


For this method it is used like this:

DrawGradientString("Hello To You", Color.blue, Color.firebrick, Drawing.Drawing2D.LinearGradientMode.Vertical)

Isn't that easy compared to VB6?

You might also like...

Comments

Michael H

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“If debugging is the process of removing software bugs, then programming must be the process of putting them in.” - Edsger Dijkstra