这个人的实现工作得很好。但是,我认为它不是Bresenham算法。它与理论有非常少的相似之处。
最后,我找到了以下版本的Bresenham直线绘制算法,它能够正常工作。
#include "utils.h"
void Bresenham(int x1, int y1, int const x2, int const y2, int color)
{
int dx = x2 - x1;
// if x1 == x2, then it does not matter what we set here
int ix((dx > 0) - (dx < 0));
dx = abs(dx) << 1;
int dy = y2 - y1;
// if y1 == y2, then it does not matter what we set here
int iy((dy > 0) - (dy < 0));
dy = abs(dy) << 1;
PlotPixel(x1, y1, color);
if (dx >= dy)
{
// error may go below zero
int error(dy - (dx >> 1));
while (x1 != x2)
{
if ((error >= 0) && (error || (ix > 0)))
{
error -= dx;
y1 += iy;
}
// else do nothing
error += dy;
x1 += ix;
PlotPixel(x1, y1, color);
}
}
else
{
// error may go below zero
int error(dx - (dy >> 1));
while (y1 != y2)
{
if ((error >= 0) && (error || (iy > 0)))
{
error -= dy;
x1 += ix;
}
// else do nothing
error += dx;
y1 += iy;
PlotPixel(x1, y1, color);
}
}
}
int main()
{
int gm = DETECT;
int gd = DETECT;
initgraph(&gm, &gd, "");
double x1 = 0;
double y1 = 0;
double r = 50;
double x2 = 0;
double y2 = 0;
double signx = 0;
double signy = 0;
for(int theta=0 ; theta<=360 ; theta++)
{
x2 = r * cos(DegreeToRad((double) theta));
y2 = r * sin(DegreeToRad((double) theta));
x1 = 5 * cos(DegreeToRad((double) theta));
y1 = 5 * sin(DegreeToRad((double) theta));
Bresenham(x1, y1, x2, y2, YELLOW);
//delay(10);
}
getch();
closegraph();
return 0;
}
原始代码非常奇怪,所以我需要您的帮助来理解它。
为什么他要将dx和dy左移,然后在计算之前再右移?
这个理论中提到的dt和ds在哪里?
根据理论,在while循环的每一步中都应该测试dt和ds。但是,这段代码并没有这样做。为什么?
理论似乎没有任何关于错误值处理的指示。代码计算
error
有什么用处?他是如何计算error
的?他如何使用error
值?测试
if(dx >= dy)
背后的逻辑是什么?
if R + Dy >= Dx Q' = Q + 1; R' = R + Dy - Dx else Q' = Q; R' = R + Dy
? - user366312