Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleMap numeric values to colors in a rainbow in Visual Basic 6
DescriptionThis example shows how to map numeric values to colors in a rainbow in Visual Basic 6.
Keywordsgraphics, colors, map values to colors, map values, Visual Basic 6, VB6
CategoriesGraphics
 

Sometimes it is useful to map values to colors. For example, intensity of color could indicate population density, agricultural yield, rainfall, or other values on a map.

The MapRainbowColor method maps a value between two extremes to a rainbow color. For example, you might want 0 to be represented by red and 100 to be represented by blue. In that case, the extreme values would be 0 and 100.

 
' Map a value to a rainbow color.
Private Function MapRainbowColor(ByVal value As Single, _
    ByVal red_value As Single, ByVal blue_value As Single) _
    As OLE_COLOR
Dim int_value As Integer
    
    ' Convert into a value between 0 and 1023.
    int_value = Int(1023 * (value - red_value) / _
        (blue_value - red_value))

    ' Map different color bands.
    If (int_value < 256) Then
        ' Red to yellow. (255, 0, 0) to (255, 255, 0).
        MapRainbowColor = RGB(255, int_value, 0)
    ElseIf (int_value < 512) Then
        ' Yellow to green. (255, 255, 0) to (0, 255, 0).
        int_value = int_value - 256
        MapRainbowColor = RGB(255 - int_value, 255, 0)
    ElseIf (int_value < 768) Then
        ' Green to aqua. (0, 255, 0) to (0, 255, 255).
        int_value = int_value - 512
        MapRainbowColor = RGB(0, 255, int_value)
    Else
        ' Aqua to blue. (0, 255, 255) to (0, 0, 255).
        int_value = int_value - 768
        MapRainbowColor = RGB(0, 255 - int_value, 255)
    End If
End Function
 
The code first converts the value into an integer between 0 and 1023. It then determines the part of the rainbow that should hold the color, subtracts an appropriate amount from the integer value to put it within the correct range, and then calculates an appropriate color.

The form's Paint event handler uses the MapRainbowColor method to fill the form with two rainbows. The on on top draws a rainbow shading from red to blue while the one on the bottom shades from blue to red.

 
' Draw rainbow colors on the form.
Private Sub Form_Paint()
Dim wid As Integer
Dim hgt As Integer
Dim hgt2 As Integer
Dim x As Integer
Dim clr As OLE_COLOR

    wid = Me.ScaleWidth
    hgt = Me.ScaleHeight
    hgt2 = Int(hgt / 2)
    For x = 0 To wid - 1
        clr = MapRainbowColor(x, 0, wid)
        Me.Line (x, 0)-(x, hgt2), clr

        clr = MapRainbowColor(x, wid, 0)
        Me.Line (x, hgt2)-(x, hgt), clr
    Next x
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated