C Colors in Graphics
In this page:
Standard Color Constants
The BGI graphics library defines 16 standard color constants numbered 0 through 15, covering common colors like BLACK, BLUE, GREEN, RED, YELLOW, and WHITE, giving you a fixed, portable palette to draw with instead of needing to specify raw RGB values.
Example: Standard Color Constants
#include <graphics.h>
int main() {
initgraph(0, 0, "");
setcolor(RED);
circle(100, 100, 30);
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Setting Foreground Color
setcolor() changes the active drawing color used for lines and shape outlines from that point forward in the program; every line() or outline shape drawn after the call uses the new color, while anything drawn earlier keeps whatever color was active when it was drawn.
Example: Setting Foreground Color
#include <graphics.h>
int main() {
initgraph(0, 0, "");
setcolor(GREEN);
line(10, 10, 100, 100);
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Setting Background Color
setbkcolor() changes the background color that fills the entire graphics window behind your drawings, distinct from setcolor() which only affects the outline color of shapes you draw afterward — changing the background recolors the whole canvas at once.
Example: Setting Background Color
#include <graphics.h>
int main() {
initgraph(0, 0, "");
setbkcolor(BLUE);
cleardevice();
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Fill Styles and Colors
setfillstyle() controls how the interior of closed shapes gets filled, taking a pattern constant (such as SOLID_FILL for a flat color or HATCH_FILL for a crosshatch pattern) together with the color to fill with, and applies to any filled shape drawn afterward.
Example: Fill Styles and Colors
#include <graphics.h>
int main() {
initgraph(0, 0, "");
setfillstyle(SOLID_FILL, RED);
bar(50, 50, 150, 150);
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Flood Filling Shapes
floodfill() fills an entire enclosed region with the current fill style and color, starting from a seed coordinate you provide inside that region and spreading outward until it hits pixels matching the specified border color, similar to a paint bucket tool.
Example: Flood Filling Shapes
#include <graphics.h>
int main() {
initgraph(0, 0, "");
circle(100, 100, 50);
setfillstyle(SOLID_FILL, YELLOW);
floodfill(100, 100, WHITE);
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: