关于Bresenham’s Line Algorithm的一些基础理解
Reference:https://www.geeksforgeeks.org/bresenhams-line-generation-algorithm/
https://www.javatpoint.com/computer-graphics-bresenhams-line-algorithm
给定两个点 A(x1,y1)=和B(x2,y2),如何完成在屏幕上绘制出线段AB呢?
原始的做法是:
// A naive way of drawing line
void naiveDrawLine(x1, x2, y1, y2)
{
m = (y2 - y1)/(x2 - x1)
for (x = x1; x <= x2; x++)
{
// Assuming that the round function finds
// closest integer to a given float.
y = round(mx + c);
print(x, y);
}
}
但是这个算法太慢了,它包括除法还可能存在浮点数的乘法,还要在每一步用round函数取整数值,而Bresenham’s Line Algorithm则避免了上述问题。
我们总是让x增加1,然后来选择下一个y值是y或者y+1,总而言之 给定任意点(Xk,Yk)我们需要在(Xk+1,Yk+1)和 (Xk+1,Yk)选择一点作为绘制的下一个点。
显然为了贴近AB直线,我们需要选择最贴近这条直线的点,这样画出来的直线才最贴近AB线。
Bresenham’s Line Algorithm 存在的限制条件
#include
#include
void drawline(int x0, int y0, int x1, int y1)
{
int dx, dy, p, x, y;
dx=x1-x0;
dy=y1-y0;
x=x0;
y=y0;
p=2*dy-dx;
while(x<x1)
{
if(p>=0)
{
putpixel(x,y,7);
y=y+1;
p=p+2*dy-2*dx;
}
else
{
putpixel(x,y,7);
p=p+2*dy;
x=x+1;
}
}
int main()
{
int gdriver=DETECT, gmode, error, x0, y0, x1, y1;
initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");
printf("Enter co-ordinates of first point: ");
scanf("%d%d", &x0, &y0);
printf("Enter co-ordinates of second point: ");
scanf("%d%d", &x1, &y1);
drawline(x0, y0, x1, y1);
return 0;
}