VGA Palettes

Depending on the video mode currently in effect, a VGA (Video Graphics Array) screen has 2, 16, or 256 color indexes chosen from a pool of 262,144 (256K) color values.

To name a color value, specify a level of intensity ranging from 0–63 for each of the red, green, and blue components. The long integer that defines a color value contains four bytes (32 bits):

The most-significant byte should contain zeros. The two high bits in the remaining three bytes should also be zero (these bits are ignored).

To mix a light red (pink), turn red all the way up, and mix in some green and blue:

The number 0x0020203FL represents this value in hexadecimal notation. You can also use the following macro:

#define RGB ( r, g, b ) (0x3F3F3FL & ((long)(b) << 16 | (g) << 8 | (r)))

To create pure yellow (100% red plus 100% green) and assign it to a variable yel, use this line:

yel = RGB( 63, 63, 0 );

For white, turn all the colors on: RGB( 63, 63, 63). For black, set all colors to 0: RGB( 0, 0, 0 ).

Once you have the color value,

1.Call _remappalette, passing a color index and a color value.

2.Call _setcolor to make that color index the current color.

3.Draw something.

The program YELLOW.C below shows how to remap a color. It draws a rectangle in color index 3 and then changes index 3 to the color value 0x00003F3FL (yellow).

/* YELLOW.C — Draws a yellow box on the screen */

/* Requires VGA or EGA */

#include <graph.h> /* graphics functions */

#include <conio.h> /* _getch */

main()

{

short int index3 = 3;

long int yellow = 0x00003F3FL;

long int old3;

if( _setvideomode( _HRES16COLOR ) )

{

/* set current color to index 3*/

_setcolor( index3 );

/* draw a rectangle in that color */

_rectangle( _GBORDER, 10, 10, 110, 110 );

/* wait for a keypress */

_getch();

/* change index 3 to yellow */

old3 = _remappalette( index3, yellow );

/* wait for a keypress */

_getch();

/* restore the old color */

_remappalette( index3, old3 );

_getch();

/* back to default mode */

_setvideomode( _DEFAULTMODE );

} else _outtext( “This program requires EGA or VGA.” );

}