夕加加 2020-04-23
DDA方法(Digital Differential Analyzer)是一种线段扫描转换算法,在一个坐标轴上以单位间隔对线段取样,从而确定另一个坐标轴上最靠近线路径的对应整数值。
方法概述
假设已知直线两端点\(A(x_{a},y_{a})\),\(B(x_{b},y_{b})\)
\(\Delta x=x_{b}-x_{a}\) \(\Delta y=y_{b}-y_{a}\)
已知直线的斜截式方程为y=m* x+b (\(m=\frac{\Delta y}{\Delta x}\))
当\(m\in(0,1)\)时,以单位x间隔(\(\delta x=1\)),逐次计算y值
当\(m\in(1,\infty)\)时,以单位y间隔(\(\delta y=1\)),逐次计算x值
对计算出的x与y,要经过四舍五入后置入像素位置
如斜率m<0时,可以通过取m绝对值,从终点向起点绘制
代码实现
#include <GL/gl.h> #include <GL/glut.h> using namespace std; void init() { glClearColor (0.0, 0.0, 0.0, 0.0); glMatrixMode (GL_PROJECTION); gluOrtho2D (0, 500, 0, 500); } inline int Round(int x) {return int(x+0.5);} void Setpoint(float x,float y) { glPointSize(2); glBegin(GL_POINTS); glVertex2i(Round(x+0.5),Round(y+0.5)); glEnd(); glFlush(); } void DDALine(int sx,int sy,int ex,int ey) { int dx=ex-sx,dy=ey-sy; float x=sx,y=sy; double step; if(abs(dx)>abs(dy)) step=abs(dx); else step=abs(dy); double addx=dx/step; double addy=dy/step; Setpoint(x,y); for(int k=0; k<=step; ++k) { x+=addx;y+=addy; Setpoint(x,y); } } void display() { glClear(GL_COLOR_BUFFER_BIT); DDALine(100,100,400,400); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowPosition(100, 100); glutInitWindowSize(500, 500); glutCreateWindow("a dda line"); init(); glutDisplayFunc(display); glutMainLoop(); return 0; }