← Back to C Course | Chapter 13: Graphics | Lesson 5 of 10

C Colors in Graphics

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

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	setcolor(RED);
	circle(100, 100, 30);
	getch();
	closegraph();
	return 0;
}

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

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	setcolor(GREEN);
	line(10, 10, 100, 100);
	getch();
	closegraph();
	return 0;
}

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

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	setbkcolor(BLUE);
	cleardevice();
	getch();
	closegraph();
	return 0;
}

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

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	setfillstyle(SOLID_FILL, RED);
	bar(50, 50, 150, 150);
	getch();
	closegraph();
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.