Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDraw a background with a moving color gradient in Visual Basic .NET
DescriptionThis example shows how to draw a background with a moving color gradient in Visual Basic .NET.
Keywordscolor gradient, moving gradient, animation, VB.NET
CategoriesGraphics, VB.NET, Multimedia
 
When the form's Timer fires, the event handler invalidates the drawing area PictureBox.

The PictureBox's Paint event handler makes a LinearGradientBrush. It defines a color blend to make the brush shade from red to green to blue. It sets the positions of the colors so red and blue are at the ends and green is positioned according to the variable m_Middle.

The program fills the PictureBox with the brush. It then updates m_Middle so the green part will move next time. If m_Middle moves beyond 0 or 1, the program changes the sign of m_Delta, the amount by which it adjusts m_Middle, so the movement goes in the other direction next time.

Finally the program draws some text over the colored background.

 
Private m_Middle As Single = 0
Private m_Delta As Single = 0.1

Private Sub tmrRotate_Tick(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles tmrRotate.Tick
    picCanvas.Invalidate()
End Sub

Private Sub picCanvas_Paint(ByVal sender As Object, ByVal e _
    As System.Windows.Forms.PaintEventArgs) Handles _
    picCanvas.Paint
    ' Draw the background gradient.
    Dim br As New LinearGradientBrush(New Point(0, 0), New _
        Point(Me.ClientSize.Width, 0), Color.Red, _
        Color.Blue)
    Dim color_blend As New ColorBlend
    color_blend.Colors = New Color() {Color.Red, _
        Color.White, Color.Blue}
    color_blend.Positions = New Single() {0, m_Middle, 1}
    br.InterpolationColors = color_blend
    e.Graphics.FillRectangle(br, Me.ClientRectangle)
    br.Dispose()

    ' Change the gradient's midpoint.
    m_Middle += m_Delta
    If (m_Middle > 1) OrElse (m_Middle < 0) Then m_Delta = _
        -m_Delta

    ' Draw some text.
    Dim string_format As New StringFormat
    string_format.Alignment = StringAlignment.Center
    string_format.LineAlignment = StringAlignment.Center
    e.Graphics.DrawString("Moving Gradient", Me.Font, _
        Brushes.Black, _
        picCanvas.ClientSize.Width \ 2, _
        picCanvas.ClientSize.Height \ 2, _
        string_format)
End Sub
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated