绘制任意斜率的直线【MidPointLine | MFC】

绘制带箭头的直线【MFC】 or 绘制带刻度的直线【MFC】 有所不同。
虽然方法内部还是使用了CDC指针和它相关的画线方法,但是整条直线的底层是使用中点画线法实现的。


代码如下:

//斜率范围为[0,1]时的中点画线法
void MidPointLine0To1(CDC *pdc, int x0, int y0, int x1, int y1, Color color) {
	pdc->SelectObject(new CPen(PS_SOLID, 1, RGB(color.r, color.g, color.b)));
	
	int dx = x1 - x0, dy = y1 - y0;
	int d = dx - 2 * dy; //初始化判别式d
	int E = -2 * dy, NE = -2 * (dy - dx);
	int x = x0, y = y0;
	while (x < x1) {
		pdc->MoveTo(*new CPoint(x, y));
		if (d > 0)d += E;
		else {
			d += NE;
			y++;
		}
		x++;
		pdc->LineTo(*new CPoint(x, y));
	}  
}

//斜率范围为[1,]时的中点画线法
void MidPointLineGt1(CDC *pdc, int x0, int y0, int x1, int y1, Color color) {
	pdc->SelectObject(new CPen(PS_SOLID, 1, RGB(color.r, color.g, color.b)));
	//pdc->MoveTo(start);

	int dx = x1 - x0, dy = y1 - y0;
	int d = 2*dx - dy; //初始化判别式d
	int E = 2 * dx, NE = 2 * (dx - dy);
	int x = x0, y = y0;
	while (x < x1) {
		pdc->MoveTo(*new CPoint(x, y));
		if (d < 0)d += E;
		else {
			d += NE;
			x++;
		}
		y++;
		pdc->LineTo(*new CPoint(x, y));
	}
}

//斜率范围为[-1,0]时的中点画线法
void MidPointLine_1To0(CDC *pdc, int x0, int y0, int x1, int y1, Color color) {
	pdc->SelectObject(new CPen(PS_SOLID, 1, RGB(color.r, color.g, color.b)));
	//pdc->MoveTo(start);

	int dx = x1 - x0, dy = y1 - y0;
	int d = -dx - 2*dy; //初始化判别式d
	int E = -2 * dy, NE = -2 * (dx + dy);
	int x = x0, y = y0;
	while (x < x1) {
		pdc->MoveTo(*new CPoint(x, y));
		if (d < 0)d += E;
		else {
			d += NE;
			y--;
		}
		x++;
		pdc->LineTo(*new CPoint(x, y));
	}
}

//斜率范围为[,-1]时的中点画线法
void MidPointLineLt_1(CDC *pdc, int x0, int y0, int x1, int y1, Color color) {
	pdc->SelectObject(new CPen(PS_SOLID, 1, RGB(color.r, color.g, color.b)));
	//pdc->MoveTo(start);

	int dx = x1 - x0, dy = y1 - y0;
	int d = -2*dx -  dy; //初始化判别式d
	int E = -2 * dy-2*dx, NE = -2 * dx;
	int x = x0, y = y0;
	while (x < x1) {
		pdc->MoveTo(*new CPoint(x, y));
		if (d < 0) {
			d += E;
			x++;
		}
		else d += NE;
		y--;
		pdc->LineTo(*new CPoint(x, y));
	}
}

void MidPointLineX(CDC *pdc, int x0, int y0, int x1, int y1, Color color) {

	int dx = x1 - x0, dy = y1 - y0;
	//斜率为[0,1]的情况
	if (dy*dx >= 0 && dy <= dx) {
		MidPointLine0To1(pdc, x0, y0, x1, y1, color);
	}
	//斜率为[1,]的情况
	if (dy*dx > 0 && dy > dx) {
		MidPointLineGt1(pdc, x0, y0, x1, y1, color);
	}
	//斜率为[-1,0]的情况
	if (dy*dx < 0 && abs(dy) <= abs(dx)) {
		MidPointLine_1To0(pdc, x0, y0, x1, y1, color);
	}
	//斜率<-1的情况
	if (dy*dx<0 && abs(dy)>abs(dx)) {
		MidPointLineLt_1(pdc, x0, y0, x1, y1, color);
	}

}
posted @ 2021-10-09 10:35  Rekord  阅读(670)  评论(0编辑  收藏  举报