Colors and Palette
Colors & Palette in graphics.h
Use color functions to control line color, background color, fill color, and palette entries. This page covers the practical differences between setcolor(), setbkcolor(), and palette APIs.
On This Page
Core Color Functions
void setcolor(int color); void setbkcolor(int color); int getcolor(void); int getbkcolor(void);
setcolor(): Sets current drawing color (lines, outlines, text).setbkcolor(): Sets graphics background color.setfillstyle(pattern, color): Sets fill color separately from outline color.
Common Color Constants
| Constant | Typical Meaning |
|---|---|
BLACK | 0, usually background default |
WHITE | 15, high-contrast line/text |
RED, GREEN, BLUE | Primary drawing colors |
LIGHTRED, LIGHTGREEN, LIGHTBLUE | Brighter variants |
YELLOW, CYAN, MAGENTA | Useful highlights |
Exact output depends on driver/mode. Keep color choices high-contrast for portability.
16 Available Colors (0-15)
This demo draws all 16 standard graphics.h colors with their index and constant name.
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
int main() {
int gd = DETECT, gm;
int i, x, y;
const char *names[16] = {
"BLACK", "BLUE", "GREEN", "CYAN",
"RED", "MAGENTA", "BROWN", "LIGHTGRAY",
"DARKGRAY", "LIGHTBLUE", "LIGHTGREEN", "LIGHTCYAN",
"LIGHTRED", "LIGHTMAGENTA", "YELLOW", "WHITE"
};
initgraph(&gd, &gm, "");
setbkcolor(BLACK);
cleardevice();
setcolor(WHITE);
outtextxy(20, 10, "graphics.h 16-color palette (0-15)");
for (i = 0; i < 16; i++) {
x = 20 + (i % 4) * 150;
y = 40 + (i / 4) * 95;
setfillstyle(SOLID_FILL, i);
bar(x, y, x + 54, y + 42);
setcolor(WHITE);
rectangle(x, y, x + 54, y + 42);
char label[64];
sprintf(label, "%2d: %s", i, names[i]);
outtextxy(x + 62, y + 15, label);
}
getch();
closegraph();
return 0;
}
Palette APIs
void setpalette(int colornum, int color); void setallpalette(struct palettetype *palette); void getpalette(struct palettetype *palette);
Palette functions remap color indexes. They are mode-dependent and may not behave the same in every environment.
Example Program
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
setbkcolor(BLACK);
cleardevice();
setcolor(WHITE);
rectangle(60, 60, 280, 220);
setfillstyle(SOLID_FILL, LIGHTBLUE);
bar(80, 80, 260, 200);
setcolor(YELLOW);
outtextxy(90, 230, "Outline and fill can use different colors");
getch();
closegraph();
return 0;
}
Common Mistakes
- Assuming
setcolor()changes fill color automatically. - Using low contrast between foreground and background.
- Relying heavily on palette remapping in incompatible modes.
Next: Fill Styles & Patterns to control shading behavior with setfillstyle() and setfillpattern().