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 color gradient
Keywordscolor gradient, background
CategoriesGraphics
 
Subroutine FadeVertical uses Line to draw different colors on a PictureBox. It sets the PictureBox's ScaleMode property to pixels to be sure it hits every pixel exactly once.

This works well on high color systems. On 256 color systems, the results are not as good. You should assign a picture with a reasonable color palette to the control.

 
' Fade colors in a vertical area of a PictureBox.
Private Sub FadeVertical(ByVal pic As PictureBox, ByVal _
    start_r As Single, ByVal start_g As Single, ByVal _
    start_b As Single, ByVal end_r As Single, ByVal end_g _
    As Single, ByVal end_b As Single, ByVal start_y, ByVal _
    end_y)
Dim hgt As Single
Dim wid As Single
Dim r As Single
Dim g As Single
Dim b As Single
Dim dr As Single
Dim dg As Single
Dim db As Single
Dim Y As Single

    wid = pic.ScaleWidth
    hgt = end_y - start_y
    dr = (end_r - start_r) / hgt
    dg = (end_g - start_g) / hgt
    db = (end_b - start_b) / hgt
    r = start_r
    g = start_g
    b = start_b
    For Y = start_y To end_y
        pic.Line (0, Y)-(wid, Y), RGB(r, g, b)
        r = r + dr
        g = g + dg
        b = b + db
    Next Y
End Sub
 
The example program uses FadeVertical in seveal ways. The following code fades a PictureBox from bright blue (0, 0, 255) to light blue (128, 255, 255).
 
Private Sub Picture1_Paint()
    FadeVertical Picture1, _
        0, 0, 255, _
        128, 255, 255, _
        0, Picture1.ScaleHeight
End Sub
 
The following code shades a PictureBox from black (0, 0, 0) to red (255, 0, 0) at the halfway point and then back to black at the bottom.
 
Private Sub Picture3_Paint()
Dim y1 As Single
Dim y2 As Single

    y1 = Picture3.ScaleHeight * 0.3
    y2 = Picture3.ScaleHeight * 0.7
    FadeVertical Picture3, _
        0, 0, 0, _
        255, 0, 0, _
        0, y1
    Picture3.Line (0, y1)-(Picture3.ScaleWidth, y2), _
        vbRed, BF
    FadeVertical Picture3, _
        255, 0, 0, _
        0, 0, 0, _
        y2, Picture3.ScaleHeight
End Sub
 
My book Custom Controls Library includes a control that produces gradients in various directions (right to left, upper left to lower right, etc.).
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated