C++第02课 类与对象 (二)
作者:互联网
1.类与对象小案例(封装按钮)
#include <graphics.h> #include <iostream> #include <string> using namespace std; class Button { public: Button() = default; Button(int x, int y, int width, int height, COLORREF inColor, COLORREF outColor, string text, COLORREF textColor) : x(x), y(y), width(width), height(height), inColor(inColor), outColor(outColor), text(text), textColor(textColor),curColor(outColor) {}//构造时可以乱序 void draw() { setfillcolor(curColor); fillrectangle(x, y, x + width, y + height); setbkmode(TRANSPARENT); settextstyle(25, 0, "楷体"); settextcolor(textColor); int tW = textwidth(text.c_str()); int tH = textheight(text.data()); int tX = x + (width - tW) / 2; int tY = y + (height - tH) / 2; outtextxy(tX, tY, text.data()); } bool mouseInButton(MOUSEMSG msg) { if (msg.x > x && msg.x<x + width && msg.y>y && msg.y < y + height) { curColor = inColor; return true; } curColor = outColor; return false; } protected: int x; int y; int width; int height; COLORREF inColor; COLORREF outColor; COLORREF curColor; string text; COLORREF textColor; }; int main() { initgraph(800, 600); Button b = { 100,100,150,50,GREEN,WHITE,"BUTTON",BLACK }; Button c(400, 100, 150, 50, GREEN, WHITE, "BUTTON_O", BLACK); MOUSEMSG msg; BeginBatchDraw(); while (1) { b.draw(); c.draw(); msg = GetMouseMsg(); if (b.mouseInButton(msg)&&msg.uMsg==WM_LBUTTONDOWN) { break; } if (c.mouseInButton(msg) && msg.uMsg == WM_LBUTTONDOWN) { break; } FlushBatchDraw(); } EndBatchDraw(); closegraph(); return 0; }
2.图形库的输入
class Button { public: Button() = default; Button(int x, int y, int width, int height, COLORREF inColor, COLORREF outColor, string text, COLORREF textColor) : x(x), y(y), width(width), height(height), inColor(inColor), outColor(outColor), text(text), textColor(textColor), curColor(outColor) {}//构造时可以乱序 void draw() { setfillcolor(curColor); fillrectangle(x, y, x + width, y + height); setbkmode(TRANSPARENT); settextstyle(25, 0, "楷体"); settextcolor(textColor); int tW = textwidth(text.c_str()); int tH = textheight(text.data()); int tX = x + (width - tW) / 2; int tY = y + (height - tH) / 2; outtextxy(tX, tY, text.data()); } bool mouseInButton(MOUSEMSG msg) { if (msg.x > x && msg.x<x + width && msg.y>y && msg.y < y + height) { curColor = inColor; return true; } curColor = outColor; return false; } protected: int x; int y; int width; int height; COLORREF inColor; COLORREF outColor; COLORREF curColor; string text; COLORREF textColor; }; int main() { initgraph(800, 600); Button b = { 100,100,150,50,GREEN,WHITE,"INPUT",BLACK }; char name[20] = ""; MOUSEMSG msg; BeginBatchDraw(); while (1) { b.draw(); msg = GetMouseMsg(); if (b.mouseInButton(msg) && msg.uMsg == WM_LBUTTONDOWN) { InputBox(name, 20);//添加的代码,增加输入框 settextcolor(WHITE); outtextxy(0, 0, name); } FlushBatchDraw(); } EndBatchDraw(); closegraph(); return 0; }
标签:02,COLORREF,width,对象,text,C++,height,int,msg 来源: https://www.cnblogs.com/creature-lurk/p/15225678.html