C Text in Graphics
In this page:
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
#include <graphics.h>
int main() {
initgraph(0, 0, "");
outtextxy(100, 100, "Hello");
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <graphics.h>
int main() {
initgraph(0, 0, "");
settextstyle(DEFAULT_FONT, HORIZ_DIR, 2);
outtextxy(50, 50, "Styled");
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <graphics.h>
int main() {
initgraph(0, 0, "");
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(150, 150, "Centered");
getch();
closegraph();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <graphics.h>
int main() {
initgraph(0, 0, "");
rectangle(50, 50, 150, 100);
outtextxy(70, 70, "Label");
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: