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

区域填充算法分为按内点填充和按边界填充

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

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

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

整个算法的过程和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();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值