C++代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//泛洪法,消耗大量空间,利用堆栈,容易造成堆栈溢出,在vs2019运行情况下需要调整安全堆栈内存大小才能正常运行
void seed_filling(HDC hdc, int x, int y, COLORREF fill_color, COLORREF boundary_color) {
COLORREF c;
c = GetPixel(hdc,x, y);
if ((c != boundary_color) && (c != fill_color)) {
SetPixel(hdc, x, y, fill_color);
seed_filling(hdc, x + 1, y, fill_color, boundary_color);
seed_filling(hdc, x - 1, y, fill_color, boundary_color);
seed_filling(hdc, x, y + 1, fill_color, boundary_color);
seed_filling(hdc, x, y - 1, fill_color, boundary_color);
/*seed_filling(hdc, x + 1, y + 1, fill_color, boundary_color);
seed_filling(hdc, x + 1, y - 1, fill_color, boundary_color);
seed_filling(hdc, x - 1, y + 1, fill_color, boundary_color);
seed_filling(hdc, x - 1, y - 1, fill_color, boundary_color);*/
}
}

//扫描线种子填色算法,节约空间
void ScanFill4(HDC hdc, int x, int y, COLORREF fill_color, COLORREF boundary_color) {
int xl, xr;
bool spanNeedFill;
POINT pt;
POINT fillPoint;
fillPoint.x = x;
fillPoint.y = y;
COLORREF c;
c = GetPixel(hdc, x, y);
stack<POINT> Stack;

pt.x = fillPoint.x;
pt.y = fillPoint.y;
Stack.push(pt);
while (!Stack.empty()) {
pt = Stack.top();
Stack.pop();
fillPoint.y = pt.y;
fillPoint.x = pt.x;
while (GetPixel(hdc, fillPoint.x, fillPoint.y) == c) {
SetPixel(hdc, fillPoint.x, fillPoint.y, fill_color);
fillPoint.x++;
}
xr = fillPoint.x - 1;
fillPoint.x = pt.x - 1;

while (GetPixel(hdc, fillPoint.x, fillPoint.y) == c) {
SetPixel(hdc, fillPoint.x, fillPoint.y, fill_color);
fillPoint.x--;
}
xl = fillPoint.x + 1;

for (int i = 0; i < 2; i++) {
fillPoint.x = xl;
if (i == 0) fillPoint.y = fillPoint.y + 1;
else fillPoint.y = fillPoint.y - 2;
while (fillPoint.x < xr) {
spanNeedFill = FALSE;
while (GetPixel(hdc, fillPoint.x, fillPoint.y) == c) {
spanNeedFill = TRUE;
fillPoint.x++;
}
if (spanNeedFill) {
pt.x = fillPoint.x - 1;
pt.y = fillPoint.y;
Stack.push(pt);
spanNeedFill = FALSE;
}
while (GetPixel(hdc, fillPoint.x, fillPoint.y) != c && fillPoint.x < xr) {
fillPoint.x++;
}
}
}
}
}