直线段扫描转换算法——Bresenham算法简介以及C++实现
目录
C++实现
参考:《计算机图形学 基础教程 第二版 》孙家广、胡事民 编著
#include<math.h>
struct CellUsignPoint_2d
{
unsigned int x;
unsigned int y;
};
//由bresenham_2d()提取的直线上点将保存在vector中
void bresenham_2d(std::vector<CellUsignPoint_2d> &cells, int x0, int y0, int x1, int y1)
{
int dx = x1 - x0;
int dy = y1 - y0;
unsigned int abs_dx = abs(dx);
unsigned int abs_dy = abs(dy);
int offset_dx = dx > 0 ? 1.0 : -1.0;
int offset_dy = dy > 0 ? 1.0 : -1.0;
CellUsignPoint_2d tmp_cell;
tmp_cell.x = x0;
tmp_cell.y = y0;
cells.push_back(tmp_cell);
// if x is dominant
if (abs_dx >= abs_dy)
{
int error = -abs_dx;
for (size_t i = 0; i < abs_dx; i++)
{
tmp_cell.x += offset_dx;
error += 2*abs_dy;
if (error > 0)
{
tmp_cell.y += offset_dy;
error -= 2*abs_dx;
}
cells.push_back(tmp_cell);
}
return;
}
// if y is dominant
else
{
int error = -abs_dy;
for (size_t i = 0; i < abs_dy; i++)
{
tmp_cell.y += offset_dy;
error += 2*abs_dx;
if (error > 0)
{
tmp_cell.x += offset_dx;
error -= 2*abs_dy;
}
cells.push_back(tmp_cell);
}
return;
}
}
简介待续···