有时我们的程序界面需要必要的文字说明,在图形界面中使用cout直接输出字符串会被图片遮挡,所以,我们要用一种特殊的方式来处理文字的显示,下面介绍两种方法。
1、显示一串固定文字
(1)设置字体透明
语法:setbkmode(TRANSPARENT);
(2)设置字体颜色
语法:settextcolor(BLUE);
(3)设置字体格式
语法:settextstyle(int weight, int height, _T("宋体"));
(4)设置字体显示位置
语法:outtextxy(int x, int y, _T("代码骑士"));
示例1:
#include<graphics.h>
#include<conio.h>
int main()
{
const int width = 640;
const int height = 480;
IMAGE picture;
initgraph(width,height);//640是画布宽度,480是画布高度
loadimage(&picture, "屏幕截图 2021-12-25 112017.jpg", width, height);
putimage(0, 0, &picture);
setbkmode(TRANSPARENT);//显示透明文字
settextcolor(BLUE);//设置字体颜色为蓝色
settextstyle(50, 0, _T("宋体"));//设置字体
outtextxy(50, 30, _T("代码骑士"));//输出文字
_getch();//暂停,等待键盘按键
closegraph();//关闭当前画布
return 0;
}
结果演示:
如果不写显示透明字体 setbkmode(TRANSPARENT); 这句语法 结果是这样的:
2、显示一串可变文字
(1)定义字符数组
语法:TCHAR text[20];
(2)定义一个变量
语法:int score = 100;
(3)将score转换成字符串
语法:
#include<iostream>
_stprintf_s(text, _T("得分:%d"), score);
(4)设置字体颜色
语法:settextcolor(BLUE);
(5)设置字体格式
语法:settextstyle(int weight, int height, _T("宋体"));
(6)设置字体显示位置
语法:outtextxy(int x, int y, text);
示例2:
#include<graphics.h>
#include<iostream>
#include<conio.h>
//using namespace std;
int main()
{
const int width = 640;
const int height = 480;
IMAGE picture;
initgraph(width,height);//640是画布宽度,480是画布高度
loadimage(&picture, "屏幕截图 2021-12-25 112017.jpg", width, height);
putimage(0, 0, &picture);
setbkmode(TRANSPARENT);//显示透明文字
TCHAR text[20];
int score = 100;
_stprintf_s(text, _T("得分:%d"), score);//将score转换成字符串
settextcolor(BLUE);//设置字体颜色为蓝色
settextstyle(50, 0, _T("宋体"));//设置字体
outtextxy(50, 30, text);//输出文字
_getch();//暂停,等待键盘按键
closegraph();//关闭当前画布
return 0;
}
结果演示:
3、总结:
掌握了两种文字显示方法。