Using the RGB Function

Let's suppose you want to mix your own colors rather than using a predefined constant value. You can do this, but it's slightly tricky. First of all, let's have a quick look at RGB, or Red Green Blue, color notation.

In RGB color notation, each primary component color (red, green, and blue) is represented by a number between 0 and 255. Table 4.2 shows some of the most common RGB values, but, of course, you can use the notation to represent almost any color.

Table 4.2: RGB Values and Colors

Color

Red value

Green value

Blue Value

Black

0

0

0

Blue

0

0

255

Green

0

255

0

Red

255

0

0

Yellow

255

255

0

White

255

255

255

If you use the Properties window to bring up the Custom palette for the BackColor or ForeColor properties, and select a color, you'll notice that the color you selected appears in the Properties window as a color swatch, followed by three numbers separated by commas.

Code Color 255 192 192

These numbers, such as 255,192,192 in the example, are the RGB values for the selected color. (Represented in this fashion, red is 255,0,0.)

To make these RGB values useful internally to VB .NET, they must be converted to a single number. Here's where the RGB function comes in. The following code will store the RGB value for red in a variable:

Dim redValue As Integer redValue = RGB (255, 0, 0)

The System.Drawing.ColorTranslator class takes the internal RGB value generated by the RGB function and allows you to set a property with it. For example, let's take 255, 192, 192, which is a kind of light pink. The following value can be assigned to a BackColor or ForeColor property:

System.Drawing.ColorTranslator.FromWin32(RGB(255, 192, 192))

Tip The ColorTranslator class, using its FromOle method, can also be used to convert VB6 hexadecimal-style RGB color values so that they can be used in VB .NET.

+1 0

Post a comment