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

C Text in Graphics

Outputting Text

outtext() prints a text string starting at the graphics system's current cursor position, while outtextxy() instead lets you specify the exact (X, Y) pixel coordinates where the text should be drawn, giving you precise placement without needing to track the cursor manually.

Example: Outputting Text

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	outtextxy(100, 100, "Hello");
	getch();
	closegraph();
	return 0;
}

Fonts and Text Styles

settextstyle() changes the font, size, and orientation used by subsequent text output, supporting orientations like HORIZ_DIR for normal left-to-right text and VERT_DIR for text rotated to read vertically, which is handy for labeling vertical axes on a chart.

Example: Fonts and Text Styles

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
	outtextxy(50, 50, "Styled");
	getch();
	closegraph();
	return 0;
}

Text Alignment

settextjustify() controls how text aligns relative to the coordinate you give it, accepting separate horizontal (LEFT_TEXT, CENTER_TEXT, RIGHT_TEXT) and vertical justification constants, so the same outtextxy() call can center, left-align, or right-align text around a fixed point.

Example: Text Alignment

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	settextjustify(CENTER_TEXT, CENTER_TEXT);
	outtextxy(150, 150, "Centered");
	getch();
	closegraph();
	return 0;
}

Displaying Numeric Values

Because outtext() and outtextxy() only accept plain string arguments, displaying a numeric value requires first converting that number into a string yourself, typically with sprintf() writing into a character buffer, before passing that buffer to the text-drawing function.

Example: Displaying Numeric Values

c
#include <graphics.h>
#include <stdio.h>
int main() {
	initgraph(0, 0, "");
	char buffer[10];
	sprintf(buffer, "%d", 42);
	outtextxy(100, 100, buffer);
	getch();
	closegraph();
	return 0;
}

Mixing Text and Shapes

Combining positioned text with drawn shapes — like a rectangle behind a centered label — is the basic technique behind building simple graphical interfaces such as menus, labeled buttons, and dashboards entirely out of the BGI drawing primitives.

Example: Mixing Text and Shapes

c
#include <graphics.h>
int main() {
	initgraph(0, 0, "");
	rectangle(50, 50, 150, 100);
	outtextxy(70, 70, "Label");
	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.