这就是扫描线种子填充程序的C实现,运行后将出现一个多边形和一个种子,由于仅是模拟,所以初始化时固定了多边形的位置和种子的位置,可以在代码中修改其位置后重新编译运行,运行时请在main()函数里设置好图形驱动程序路径,因人而异了。
#include<graphics.h>
#include<stdio.h>
#include<malloc.h>
#define bordercolor 15
#define backcolor 0
#define seedcolor 4
#define fillcolor 10
typedef struct Point
{int x;
int y;
}point;
typedef struct Stack
{point *base;
point *top;
}*stack;
void initstack(stack s)
{(*s).base=(point*)malloc(sizeof(point));
if(!(*s).base)exit(1);
(*s).top=(*s).base;
}
void push(stack s,point p)
{*((*s).top)=p;
(*s).top++;
}
int stackempty(stack s)
{if((*s).top==(*s).base)return(1);
else return(0);
}
point pop(stack s)
{(*s).top--;
return(*((*s).top));
}
void drawgraphics()
{rectangle(100,100,539,299);
rectangle(150,150,489,249);
}
point produceseed()
{point p;
p.x=125;
p.y=200;
return(p);
}
void intostack(stack s,int y0,int xl,int xr)
{int x,y;
point tm;
for(x=xl,y=y0;x<=xr&&x<getmaxx();x++)
{if((x!=xr&&getpixel(x,y)==backcolor&&getpixel(x+1,y)!=backcolor)||
(x==xr&&getpixel(x,y)==backcolor))
{tm.x=x;
tm.y=y;
push(s,tm);
putpixel(x,y,seedcolor);
}
if(x==xr&&getpixel(x,y)==backcolor)break;
}
}
void fillgraphics()
{int xl=0,xr=getmaxx(),x,y;
point seed;
stack s=NULL;
seed=produceseed();
putpixel(seed.x,seed.y,seedcolor);
getch();
initstack(s);
push(s,seed);
while(!stackempty(s))
{seed=pop(s);
for(x=seed.x,y=seed.y;getpixel(x,y)==backcolor||getpixel(x,y)==seedcolor;x++)
{putpixel(x,y,fillcolor);
}
xr=x-1;
for(x=seed.x-1,y=seed.y;getpixel(x,y)==backcolor||getpixel(x,y)==seedcolor;x
--)
{putpixel(x,y,fillcolor);
}
xl=x+1;
intostack(s,seed.y+1,xl,xr);
intostack(s,seed.y-1,xl,xr);
getch();
}
}
main()
{int driver=DETECT,mode;
registerbgidriver(EGAVGA_driver);
initgraph(&driver,&mode,"");
drawgraphics();
fillgraphics();
outtextxy(180,20,"Scanline filling graphics finished!");
getch();
closegraph();
}
评论