Bresenham算法画直线

时间:2021-05-26 12:00:34

Bresenham算法画直线

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
}


Bresenham算法画直线