使用EasyX c++库
中点算法直线绘制
//中点算法划线:横向直线绘制 void DDAline(int x1, int y1, int x2, int y2, int color) { int x; float dx, dy, y, k; dx = x2 - x1, dy = y2 - y1; if (dx == 0) { for (y = min(y1, y2); y < max(y1, y2); y++) { putpixel(x1, y, color); } return; } k = dy / dx; if (x1 < x2)y = y1; else y = y2; for (x = min(x1, x2); x <= max(x1, x2); x++) { putpixel(x, int(y + 0.5), color); y = y + k; } }
Bresenham算法直线绘制
//Bresenham算法画线:棋盘纵向网格绘制 void Bresenhamline(int x1, int y1, int x2, int y2, int color) { int x; float dx, dy, y, e; dx = x2 - x1, dy = y2 - y1; if (dx == 0) { for (y = min(y1, y2); y < max(y1, y2); y++) { putpixel(x1, y, color); } return; } if (dy == 0) { for (x = min(x1, x2); x < max(x1, x2); x++) { putpixel(x, y1, color); } return; } x = x1, y = y1; if (x1 < x2) { if (y1 < y2) { if (dy <= dx) { e = -dx; for (int i = 0; i <= dx; i++) { putpixel(x, y, color); x++, e = e + 2 * dy; if (e >= 0) { y++; e = e - 2 * dx; } } } else { e = -dy; for (int i = 0; i <= dy; i++) { putpixel(x, y, color); y++, e = e + 2 * dx; if (e >= 0) { x++; e = e - 2 * dy; } } } } else { if (-dy <= dx) { e = -dx; for (int i = 0; i <= dx; i++) { putpixel(x, y, color); x++, e = e + 2 * dy; if (e <= 0) { y--; e = e + 2 * dx; } } } else { e = -dy; for (int i = 0; i <= -dy; i++) { putpixel(x, y, color); y--, e = e + 2 * dx; if (e >= 0) { x++; e = e + 2 * dy; } } } } } else { //x = x2, y = y2; if (y1 < y2) { if (dy <= -dx) { e = -dx; for (int i = 0; i <= -dx; i++) { putpixel(x, y, color); x--, e = e + 2 * dy; if (e >= 0) { y++; e = e + 2 * dx; } } } else { e = -dy; for (int i = 0; i <= dy; i++) { putpixel(x, y, color); y++, e = e - 2 * dx; if (e >= 0) { x--; e = e - 2 * dy; } } } } else { if (-dy <= -dx) { e = -dx; for (int i = 0; i <= -dx; i++) { putpixel(x, y, color); x--, e = e + 2 * dy; if (e <= 0) { y--; e = e - 2 * dx; } } } else { e = -dy; for (int i = 0; i <= -dy; i++) { putpixel(x, y, color); y--, e = e + 2 * dx; if (e <= 0) { x--; e = e - 2 * dy; } } } } } }
主函数执行程序
//绘制网格线 //直线整体纵向平移需要更改坐标(y1,y2)相同单位 DDAline(x1, y1 - 50, x2, y2 - 50, BLACK); DDAline(x1, y1, x2, y2, BLACK); //直线整体横向平移需要更改坐标(x1,x2)相同单位 Bresenhamline(300, 40, 300, 440, BLACK); Bresenhamline(300 - 50, 40, 300 - 50, 440, BLACK);
标签:x1,int,Bresenham,画线,x2,算法,dy,y1,y2 From: https://www.cnblogs.com/Cyruswong/p/18433755