1. 程式人生 > >Bresenham演算法畫直線

Bresenham演算法畫直線

void Bresenham_line(CDC *pDC, int x0, int y0, int x1, int y1, long color)
{
	int dx = abs(x1 - x0);
	int dy = abs(y1 - y0);
	int x = x0;
	int y = y0;
	int stepX = 1;
	int stepY = 1;
	if(x0 > x1)  //從右向左畫
		stepX = -1;
	if(y0 > y1)
		stepY = -1;
	
	if(dx > dy)  //沿著最長的那個軸前進
	{
		int e = dy * 2 - dx;
		for(int i=0; i<=dx; i++)
		{
			pDC->SetPixel(x, y, color);
			x += stepX;
			e += dy;
			if(e >= 0)
			{
				y += stepY;
				e -= dx;
			}
		}
	}
	else
	{
		int e = 2 * dx - dy;
		for(int i=0; i<=dy; i++)
		{
			pDC->SetPixel(x, y, color);
			y += stepY;
			e += dx;
			if(e >= 0)
			{
				x += stepX;
				e -= dy;
			}
		}
	}
}

void CDrawView::OnDraw(CDC* pDC)
{
	CDrawDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	Bresenham_line(pDC, 50, 50, 300, 150, RGB(255, 0, 0));
	Bresenham_line(pDC, 50, 50, 150, 300, RGB(0, 255, 0));
	Bresenham_line(pDC, 400, 400, 50, 50, RGB(0, 0, 255));
	Bresenham_line(pDC, 300, 150, 150, 300, RGB(255, 255, 0));
	// TODO: add draw code for native data here
}