在任何二维平面上,如果我们连接两个点(x0,y0)和(x1,y1),我们得到一条线段。但在计算机图形学的情况下,我们不能直接连接任何两个坐标点,因为我们应该计算中间点的坐标,并为每个中间点放置一个像素,该像素具有所需的颜色,并借助以下函数: C中的像素(x,y,K) ,其中(x,y)是坐标,K表示某种颜色。 例如:
null
Input: For line segment between (2, 2) and (6, 6) :we need (3, 3) (4, 4) and (5, 5) as our intermediatepoints.Input: For line segment between (0, 2) and (0, 6) :we need (0, 3) (0, 4) and (0, 5) as our intermediatepoints.
为了使用图形功能,我们的系统输出屏幕被视为一个坐标系,其中左上角的坐标为(0,0),当我们向下移动时,我们的y坐标增加,当我们向右移动时,任何点(x,y)的x坐标增加。 现在,为了生成任何线段,我们需要中间点,为了计算它们,我们可以使用一种叫做 DDA(数字微分分析仪) 线条生成算法。
DDA算法: 将该线的一个点视为(x0,y0),并将该线的第二点设为(x1,y1)。
// calculate dx , dydx = X1 - X0;dy = Y1 - Y0;// Depending upon absolute value of dx & dy// choose number of steps to put pixel as// steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy)steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);// calculate increment in x & y for each stepsXinc = dx / (float) steps;Yinc = dy / (float) steps;// Put pixel for each stepX = X0;Y = Y0;for (int i = 0; i <= steps; i++){ putpixel (round(X),round(Y),WHITE); X += Xinc; Y += Yinc;}
C
// C program for DDA line generation #include<stdio.h> #include<graphics.h> #include<math.h> //Function for finding absolute value int abs ( int n) { return ( (n>0) ? n : ( n * (-1))); } //DDA Function for line generation void DDA( int X0, int Y0, int X1, int Y1) { // calculate dx & dy int dx = X1 - X0; int dy = Y1 - Y0; // calculate steps required for generating pixels int steps = abs (dx) > abs (dy) ? abs (dx) : abs (dy); // calculate increment in x & y for each steps float Xinc = dx / ( float ) steps; float Yinc = dy / ( float ) steps; // Put pixel for each step float X = X0; float Y = Y0; for ( int i = 0; i <= steps; i++) { putpixel (round(X),round(Y),RED); // put pixel at (X,Y) X += Xinc; // increment in x at each step Y += Yinc; // increment in y at each step delay(100); // for visualization of line- // generation step by step } } // Driver program int main() { int gd = DETECT, gm; // Initialize graphics function initgraph (&gd, &gm, "" ); int X0 = 2, Y0 = 2, X1 = 14, Y1 = 16; DDA(2, 2, 14, 16); return 0; } |
输出:
优势:
- 该算法简单,易于实现。
- 它避免了使用时间复杂度高的多个操作。
- 它比直接使用直线方程更快,因为它不使用任何浮点乘法,并且计算直线上的点。
缺点:
- 它处理舍入运算和浮点运算,因此具有很高的时间复杂度。
- 由于它依赖于方向,因此端点精度较差。
- 由于浮点表示法的精度有限,它会产生累积误差。
Bresenham的直线生成算法 本文由 希瓦姆·普拉丹(anuj_charm) .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END