基于 M F C MFC MFC的种子填充算法的实现
【注】:使用的 I D E IDE IDE是VS 2017
多边形填充算法包括:扫描线填充,边缘填充,以及种子填充。此处所给的是种子填算法。
1、新建 M F C MFC MFC项目
此处就不再赘述,没有 M F C MFC MFC基础的可以先看第一个MFC程序。
项目名为 P o l y g o n f i l l Polygonfill Polygonfill
2、全局变量
CPoint spt[7], s_point;
int flag=0;
3、窗口初始化
void CPolygonfillView::OnDraw(CDC* pDC)
{
CPolygonfillDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
CPen newpen(PS_SOLID, 1, RGB(0, 0, 255)); //多边形边为蓝色
CPen *old = pDC->SelectObject(&newpen);
pDC->TextOutW(20, 20, L"双击鼠标左键,生产多边形");
pDC->TextOutW(20, 50, L"先在多边形内部单击鼠标左键,选择种子点,然后单击功能菜单实现填充");
pDC->SelectObject(old);
}
4、多边形初始化
资源视图中,单击右键 P o l y g o n f i l l Polygonfill Polygonfill项目,选择类向导。
在消息中选择 W M _ L B u t t o n D b l C l k WM\_LButtonDblClk WM_LButtonDblClk。
void CPolygonfillView::OnLButtonDblClk(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
RedrawWindow();
CDC *pDC = GetDC();
CPen newpen(PS_SOLID, 1, RGB(0, 0, 255));
CPen * old = pDC->SelectObject(&newpen);
spt[0] = CPoint(100, 100);
spt[1] = CPoint(250, 100);
spt[2] = CPoint(250, 250);
spt[3] = CPoint(100, 250);
spt[4] = CPoint(150, 200);
spt[5] = CPoint(90, 150);
spt[6] = CPoint(160, 150);
spt[7] = CPoint(100, 100);
pDC->Polyline(spt, 8);
pDC->SelectObject(old);
ReleaseDC(pDC);
flag = 1;
CView::OnLButtonDblClk(nFlags, point);
}
5、种子初始化
同理,在类向导的消息中,选择 W M _ L B u t t o n D o w n WM\_LButtonDown WM_LButtonDown。
void CPolygonfillView::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
s_point = point;
flag = 2;
CView::OnLButtonDown(nFlags, point);
}
6、填充算法实现
添加事件处理程序 S e e d f i l l Seedfill Seedfill
void CPolygonfillView::OnSeedfill()
{
// TODO: 在此添加命令处理程序代码
CWindowDC dc(this);
int fill = RGB(0, 255, 0);
int boundary = RGB(0, 0, 255);
int x, y, p0, pmin, pmax;
if (flag != 2) {
if (flag == 0)
MessageBox(L"请先双击左键,生产多边形", L"警告!");
if (flag == 1)
MessageBox(L"请先单击左键,选择种子点", L"警告!");
return;
}
for (int m = 1; m < 7; m++)
{
for (int n = 0; n < 7 - m; n++)
{
if (spt[n].y < spt[n + 1].y)
{
p0 = spt[n].y;
spt[n].y = spt[n + 1].y;
spt[n + 1].y = p0;
}
}
}
pmax = spt[0].y;
pmin = spt[6].y;
x = s_point.x;
y = s_point.y;
for (; y <= pmax; y++)
{
int current = dc.GetPixel(x, y);
while ((current != boundary) && (current != fill))
{
dc.SetPixel(x, y, fill);
x++;
current = dc.GetPixel(x, y);
}
x = s_point.x;
x--;
current = dc.GetPixel(x, y);
while ((current != boundary) && (current != fill))
{
dc.SetPixel(x, y, fill);
x--;
current = dc.GetPixel(x, y);
}
x = s_point.x;
}
x = s_point.x;
y = s_point.y - 1;
for (; y >= pmin + 2; y--)
{
int current = dc.GetPixel(x, y);
while ((current != boundary) && (current != fill))
{
dc.SetPixel(x, y, fill);
x++;
current = dc.GetPixel(x, y);
}
x = s_point.x;
x--;
current = dc.GetPixel(x, y);
while ((current != boundary) && (current != fill))
{
dc.SetPixel(x, y, fill);
x--;
current = dc.GetPixel(x, y);
}
x = s_point.x;
}
}