Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 48,171 times

Related Categories

Drawing A Color Gradient

Michael H

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?

Comments

  • Re: how to make label background transparent?

    Posted by thorst on 30 Jan 2008

    Very cool. I tried modifying this code to work with a group box, and instead of drawing colors id like it to have a transparent background. Well, when i was doing this it would erase the boarder th...

  • Re: how to make label background transparent?

    Posted by f00 on 22 Sep 2006

    this adds the gradient background, then re-draws the text.


    In VB.Net:


    Private Su...

  • how to make label background transparent?

    Posted by mushu on 24 Sep 2004

    Thanks for this great code, very cool. But when I put a label on the form, the background color of the label shows up as a solid color block. How can I make the label background color transparent? The...

  • drawing a color gradient

    Posted by robertd33 on 04 Mar 2004

    first, thanks for these.

    is there any way to apply the text gradient to normal text, i.e., labels? i haven't been able to tweak it enough to do so. any ideas?

    or maybe a button gradient, or othe...