Simplified Bresenham's line algorithm: What does it *exactly* do?

喜欢而已 提交于 2019-11-28 21:31:33

There are various forms of equations for a line, one of the most familiar being y=m*x+b. Now if m=dy/dx and c = dx*b, then dx*y = dy*x + c. Writing f(x) = dy*x - dx*y + c, we have f(x,y) = 0 iff (x,y) is a point on given line.

If you advance x one unit, f(x,y) changes by dy; if you advance y one unit, f(x,y) changes by dx. In your code, err represents the current value of the linear functional f(x,y), and the statement sequences

    err = err - dy;
    x1 = x1 + sx;

and

    err = err + dx;
    y1 = y1 + sy;

represent advancing x or y one unit (in sx or sy direction), with consequent effect on the function value. As noted before, f(x,y) is zero for points on the line; it is positive for points on one side of the line, and negative for those on the other. The if tests determine whether advancing x will stay closer to the desired line than advancing y, or vice versa, or both.

The initialization err = dx - dy; is designed to minimize offset error; if you blow up your plotting scale, you'll see that your computed line may not be centered on the desired line with different initializations.

Just want to add one bit of "why" information to jwpat's excellent answer.

The point of using the f(x) = dy*x - dx*y + c formulation is to speed up the calculation. This formulation uses integer arithmetic (faster), whereas the traditional y = mx + b formulation uses floating point arithmetic (slower).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!