以下代码实现了在绘图区画任意大小矩形,并保存在shapes数组中。
请问如何实现用鼠标点击任意一个矩形,就可以给他填充颜色。
自己已经看过具有类似功能的涂格子游戏的范例,但是涂格子游戏中每个矩形大小相等,坐标可以通过相应规律计算得出,而本例中矩形可以任意大小。斯认为其中最重要的几点,第一是在鼠标点击之后,能够得到距离鼠标点击处最近的矩形的坐标,请问如何得到?第二,假设此时先画了一个大矩形,然后在大矩形里画了一个小矩形,(类似“回”字),现在要给这两个矩形填充不同的颜色,并且不能让大矩形的颜色覆盖掉小矩形(不管先给哪一个矩形上色都不会覆盖),请问如何实现?
#include <iostream>
#include <graphics.h>
#include <conio.h>
#include <vector>
using namespace std;
class Rect
{
private:
int x1;
int y1;
int x2;
int y2;
COLORREF color; //颜色
int line_Th; //线宽
public:
Rect();
Rect(int x1, int y1, int x2, int y2, COLORREF color, int line_Th);
~Rect();
void line_draw();
};
Rect::Rect()
{
}
Rect::Rect(int x1, int y1, int x2, int y2, COLORREF color, int line_Th)
{
this->x1 = x1;
this->y1 = y1;
this->x2 = x2;
this->y2 = y2;
this->color = color;
this->line_Th = line_Th;
}
Rect::~Rect()
{
}
void Rect::line_draw()
{
setlinecolor(this->color);
setlinestyle(PS_SOLID, this->line_Th);
rectangle(this->x1, this->y1, this->x2, this->y2);
}
class Canvas
{
private:
Rect r;
ExMessage msg;
int begx; //鼠标按下时x坐标
int begy; //鼠标按下时y坐标
bool isPress = false; //鼠标是否按下
vector<Rect*> Shapes;
public:
Canvas();
~Canvas();
ExMessage* Get_message();
void LMouseButtonDown(ExMessage* msg);
void LMouseButtonUp(ExMessage* msg);
void mouseMove(ExMessage* msg);
void SetVector(Rect* r);
Rect* GetVector(int i);
void painting();
};
Canvas::Canvas()
{
}
Canvas::~Canvas()
{
}
ExMessage* Canvas::Get_message()
{
return &this->msg;
}
void Canvas::LMouseButtonDown(ExMessage* msg)
{
this->isPress = true;
//记录鼠标按下时的坐标
this->begx = msg->x;
this->begy = msg->y;
cout << "mouseButtonDown" << endl;
}
void Canvas::LMouseButtonUp(ExMessage* msg)
{
this->isPress = false;
Rect* r = new Rect(this->begx, this->begy, msg->x, msg->y, BLUE, 2);
this->SetVector(r);
cout << "mouseButtonUp" << this->Shapes.size() << endl;
}
void Canvas::mouseMove(ExMessage* msg)
{
//若鼠标左键按下并移动,就开始绘制
if (this->isPress)
{
cleardevice();
setlinecolor(BLUE);
rectangle(this->begx, this->begy, msg->x, msg->y);
}
cout << "mouseMove" << endl;
}
void Canvas::SetVector(Rect* r)
{
this->Shapes.push_back(r);
}
Rect* Canvas::GetVector(int i)
{
return this->Shapes[i];
}
void Canvas::painting()
{
while (true)
{
//绘制
for (int i = 0; i < this->Shapes.size(); i++)
{
this->GetVector(i)->line_draw();
}
while (peekmessage(this->Get_message(), EX_MOUSE))
{
switch (this->Get_message()->message)
{
case WM_LBUTTONDOWN:
this->LMouseButtonDown(this->Get_message());
break;
case WM_LBUTTONUP:
this->LMouseButtonUp(this->Get_message());
break;
case WM_MOUSEMOVE:
this->mouseMove(this->Get_message());
break;
}
}
}
}
int main()
{
initgraph(1080, 750, EX_SHOWCONSOLE);
Canvas canvas;
canvas.painting();
_getch();
return 0;
}