mfc扫描线种子填充算法----计算机图形学实验
最近刚刚学了计算机图形学,自己动手做了几个实验,下面介绍扫描线种子填充算法实现画一个老虎,代码有很多不够精简的地方。
具体算法推荐一篇文章(侵删,我在其基础上稍加改动)
详细的解释扫描线算法
1.调用系统画线函数先画一个老虎轮廓:
部分代码:
void CTiger1View::DrawTiger()
{
CDC *pDC=GetDC();
mpDC=pDC;
POINT ptpolygon1[3]={{40,20},{60,60},{80,40}};
mpDC->Polygon(ptpolygon1,3);
POINT p1[3]={{280,20},{260,60},{240,40}};
mpDC->Polygon(p1,3);
mpDC->MoveTo(40,20);
mpDC->LineTo(20,40);
mpDC->LineTo(8,60);
mpDC->LineTo(10,80);
mpDC->LineTo(20,90);
mpDC->LineTo(40,100);
mpDC->LineTo(60,60);//耳朵
mpDC->MoveTo(280,20);
mpDC->LineTo(300,40);
mpDC->LineTo(312,60);
mpDC->LineTo(310,80);
mpDC->LineTo(300,90);
mpDC->LineTo(280,100);
mpDC->LineTo(260,60);
mpDC->MoveTo(80,40);
mpDC->LineTo(160,14);
mpDC->LineTo(240,40);
POINT ptpolygon2[6]={{45,100},{65,80},{55,100},{77,206},{95,210},{71,220}};
mpDC->Polygon(ptpolygon2,6);//条纹2
POINT p2[6]={{275,100},{255,80},{265,100},{243,206},{225,210},{249,220}};
mpDC->Polygon(p2,6);
POINT ptpolygon3[4]={{40,100},{54,200},{40,240},{44,200}};
POINT p3[4]={{280,100},{266,200},{280,240},{276,200}};
mpDC->Polygon(ptpolygon3,4);
mpDC->Polygon(p3,4);//条纹1
mpDC->MoveTo(41,140);
mpDC->LineTo(0,220);
mpDC->LineTo(40,240);//左脸
mpDC->MoveTo(279,140);
mpDC->LineTo(320,220);
mpDC->LineTo(280,240);
POINT ptpolygon4[3]={{40,240},{96,280},{44,262}};
mpDC->Polygon(ptpolygon4,3);//下条纹
POINT p4[3]={{280,240},{224,280},{276,262}};
mpDC->Polygon(p4,3);
mpDC->MoveTo(96,280);
mpDC->LineTo(96,240);
mpDC->LineTo(125,200);
mpDC->MoveTo(224,280);
mpDC->LineTo(224,240);
mpDC->LineTo(195,200);
POINT ptpolygon5[3]={{60,230},{80,260},{56,244}};
mpDC->Polygon(ptpolygon5,3);//小条纹
POINT ptpolygon6[5]={{84,120},{126,160},{110,175},{110,216},{72,160}};
mpDC->Polygon(ptpolygon6,5);//眼
POINT p5[3]={{260,230},{240,260},{264,244}};
mpDC->Polygon(p5,3);//小条纹
POINT p6[5]={{236,120},{194,160},{210,175},{210,216},{248,160}};
mpDC->Polygon(p6,5);//眼
}
2.扫描线种子填充算法
部分代码:
void CTiger1View::scan_seed_fill(int x, int y, COLORREF oldColor, COLORREF newColor)
{
stack<Seed> sp;
int xl,xr;
bool spanNeedfill;
Seed pt;
pt.x=x;pt.y=y;
sp.push(pt);
while(!sp.empty())
{
pt=sp.top();sp.pop();
y=pt.y;x=pt.x;
while(mpDC->GetPixel(x,y)==oldColor)//向右填充
{
mpDC->SetPixel(x,y,newColor);
x++;
}
xr=x-1;x=pt.x-1;
while(mpDC->GetPixel(x,y)==oldColor)//向左填充
{
mpDC->SetPixel(x,y,newColor);
x--;
}
xl=x+1;
//处理上面一条扫描线
x=xl;y=y+1;
while(x<=xr)
{
spanNeedfill=false;
while(mpDC->GetPixel(x,y)==oldColor)
{
spanNeedfill=true;
x++;
}
if(spanNeedfill)
{
pt.x=x-1;pt.y=y;
sp.push(pt);
spanNeedfill=false;
}
while((mpDC->GetPixel(x,y)!=oldColor)&&x<=xr) x++;
}
}
}