編譯器:VS2013
該算法相對邊緣填充算法萊說,效率較高來說,選取一個頂點的橫坐標為柵欄,將直線和柵欄之間進行填充,如果顏色為背景色,則填充填充色,否則則填充背景色
代碼:
1 // 柵欄填充算法.cpp : 定義控制台應用程序的入口點。 2 // 3 4 #include "stdafx.h" 5 #include<stdio.h> 6 #include"graphics.h" 7 #include<stdlib.h> 8 9 //函數聲明 10 void fencefill(int a[], int x,int n);//柵欄填充算法實現 11 void putcolor(int Xmin, int Xmax, int k);//着色函數 12 13 int main() 14 { 15 int gdriver = DETECT, gmove, x,y,n; 16 17 printf("please input the number of point\n"); 18 scanf_s("%d", &n); 19 int *a=(int *)malloc((n+2)*sizeof(int));//動態分配內存 20 21 for (y = 0; y < n + 2; y++) 22 scanf_s("%d", &a[y]); 23 24 x = a[n];//選取a[n]為柵欄 25 26 initgraph(&gdriver, &gmove, ""); 27 28 setcolor(YELLOW); 29 drawpoly(n/2+1, a);//畫出多邊形 30 fencefill(a, x,n);//柵欄填充算法實現 31 drawpoly(n/2+1, a);//再處理一次邊界 32 33 //因柵欄被處理兩次,所以再次填充柵欄一列 34 for (y = a[n+1]+1; getpixel(x, y) != YELLOW; y++) 35 putpixel(x, y, YELLOW); 36 37 system("pause"); 38 39 closegraph(); 40 41 return 0; 42 } 43 44 //柵欄填充算法實現 45 void fencefill(int a[], int x,int n) 46 { 47 int i, y, Xmin, Xmax, Ymax, Ymin,xi; 48 49 //循環數組a 50 for (i = 0; i < n; i = i + 2) 51 { 52 //判斷縱坐標大小 53 Ymax = (a[i + 1] > a[i + 3]) ? a[i + 1] : a[i + 3]; 54 Ymin = (a[i + 1] <= a[i + 3]) ? a[i + 1] : a[i + 3]; 55 56 //行處理 57 for (y = Ymin; y < Ymax; y++) 58 { 59 //利用直線關系求得y=k時x對應的坐標 60 xi = (y - a[i + 1])*(a[i + 2] - a[i]) / (a[i + 3] - a[i + 1]) + a[i]; 61 62 //求x與柵欄大小關系 63 Xmax = (xi > x) ? xi : x; 64 Xmin = (xi <= x) ? xi : x; 65 66 putcolor(Xmin, Xmax, y);//着色函數 67 } 68 } 69 70 } 71 72 //着色函數 73 void putcolor(int Xmin, int Xmax, int y) 74 { 75 while (Xmin <= Xmax) 76 { 77 if (getpixel(Xmin, y) == YELLOW) 78 putpixel(Xmin, y, BLACK); 79 else 80 putpixel(Xmin, y, YELLOW); 81 82 Xmin++; 83 } 84 }
結果: