mfc掃描線種子填充算法----計算機圖形學實驗

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.掃描線種子填充算法

部分代碼:spa

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++;
		}
	}
}

在這裏插入圖片描述

下載連接

源代碼.net

相關文章
相關標籤/搜索