您的位置:首页 > 其它

【寒江雪】区域填充算法递归实现

2016-11-17 00:09 246 查看
区域填充算法分为按内点填充和按边界填充

该算法假设区域内有一个像素已知。由此像素出发,利用连通性找到其他像素。

连通性可以是四连通(上下左右方向)和八连通(上下左右,对角线),在搜索的过程中对每一个方向进行尝试

按边界填充需要先把多边形的边进行标记。之后再调用算法进行填充。

整个算法的过程和DFS(深度优先搜索)的思想是一模一样的。

代码如下:

VOID
CGraphicDlg::FloodBoundaryFill(int
x, int
y,COLORREF
edgeColor,COLORREF
newColor)

{

   
if (GetCoordinatePixel(x,y) ==
edgeColor)return;

   
int addx[4] = { -1,0,1,0 };

   
int addy[4] = { 0,-1,0,1 };

   
int nx, ny;

    DrawRectange(x,
y, 0, 0, newColor);

   
for (int i = 0; i < 4; i++) {

        nx =
x + addx[i];

        ny =
y + addy[i];

       
if (nx>=-400&&nx<=400&&ny>=-300&&ny<=300&&GetCoordinatePixel(nx,ny)!=
newColor) {

            FloodFill(nx, ny,
edgeColor, newColor);

        }

    }

   

   
return VOID();

}

如需要改为八方向的只需要修改addx数组和addy数组,不过个人觉得,八方向覆盖面广,调用层次过多,导致内存消耗非常大。

内点填充算法假设一个点已知,从这个点出发,将所有其他与该点不同的点进行填充。

VOID
CGraphicDlg::FloodPointFill(int
x, int
y, COLORREF
oldColor, COLORREF
newColor)

{

   
int nx, ny;

   
int addx[4] = { -1,0,1,0 };

   
int addy[4] = { 0,-1,0,1 };

   
if (GetCoordinatePixel(x,
y) == oldColor) {

        DrawRectange(x,
y, 0, 0, newColor);

       
for (int i = 0; i < 4; i++) {

            nx =
x + addx[i];

            ny =
y + addy[i];

            if(nx>=-400&&nx<=400&&ny>=-300&&ny<=300
       &&GetCoordinatePixel(nx,ny)!=newColor)

                  FloodPointFill(nx, ny,
oldColor, newColor);

        }

    }

   
return VOID();
}
当然,改用栈来模拟递归也不是不可以。没有实践过,可以尝试 


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: