easyx是实现c/c++的图形库,没有封装好的组件,需要手动完成。
思路是画一个长方形,在长方形中水平、垂直居中显示文字。
设置文字的位置思路是
文字x坐标=按钮边框的起始位置x+(按钮的宽度-文字宽度)/2
文字y坐标=按钮边框的起始位置y+(按钮的高度-文字高度)/2
按钮构造好后,需要获取鼠标的位置坐标,判断鼠标是否在按钮的宽度、高度的范围内,若在此范围内,进行相应的事件函数。
#include// 引用图形库头文件 #include #include #include void button(int x,int y,int w,int h,TCHAR * text) { setbkmode(TRANSPARENT); setfillcolor(GREEN); fillroundrect(x,y,x+w,y+h,10,10); // 输出字符串(MBCS 字符集) TCHAR s1[] = L"黑体"; settextstyle(30,0,s1); TCHAR s[50] = L"hello"; int tx = x + (w - textwidth(text)) / 2; int ty = y + (h - textheight(text)) / 2; outtextxy(tx, ty, text); } int main() { initgraph(640, 480); // 创建绘图窗口,大小为 640x480 像素 setbkcolor(BLUE); cleardevice(); TCHAR s[50] = L"1.读取点云"; TCHAR s1[50] = L"2.分割点云"; TCHAR s2[50] = L"3.单个树木"; TCHAR s3[50] = L"4.树木重建"; button(220,50,170,50,s); button(220, 150, 170, 50, s1); button(220, 250, 170, 50, s2); button(220, 350, 170, 50, s3); ExMessage msg; while (true) { if (peekmessage(&msg, EM_MOUSE)) { switch (msg.message) { case WM_LBUTTONDOWN: if (msg.x >= 220 && msg.x <= 220 + 170 && msg.y >= 50 && msg.y <= 50 + 50) { outtextxy(200, 200, s); } if (msg.x >= 220 && msg.x <= 220 + 170 && msg.y >= 150 && msg.y <= 150 + 50) { outtextxy(200, 200, s1); } if (msg.x >= 220 && msg.x <= 220 + 170 && msg.y >= 250 && msg.y <= 250 + 50) { outtextxy(200, 200, s2); } if (msg.x >= 220 && msg.x <= 220 + 170 && msg.y >= 350 && msg.y <= 350 + 50) { outtextxy(200, 200, s3); } break; default: break; } } } return 0; }
结果如图所示
点击后效果如图:



