参考《计算机图形学》 Donald.Hearn
书中给出了斜率k在0-1之间的推导过程
在k>=1时以y方向为单位步长递增,此时有x=(y-b)/b;
d(low)=x-x(k)=( y(k+1)-b )/m-x(k);
d(upper)=x(k+1)-x=x(k)+1-( y(k+1)-b )/m;
p(k)=dx*(d(low)-d(upper))=2*dx*(y(k)+1-b)-2*dy*x(k)-dx;
可以推出
p(k+1)=p(k)+2*dx-2*dy(x(k+1)-x(k));
其中x(k+1)-x(k)的值取决于p(k)的符号
将直线方程式和斜率m=dy/dx带入p(k)的表达式可以得出
p(0)=dy,由此可以写出斜率大于1时的实现,
同理可以按此方法得出斜率在(-1,0)和斜率小于-1时的情况,或者可以根据对称性得出
#include #include GLint winWidth=640,winHeight=480; void init() { glClearColor(1.0,1.0,1.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,winWidth,0,winHeight); } ///以下为bresenham实现 inline void swap(GLint& a,GLint& b){GLint t=a;a=b;b=t;} //在屏幕上画一个点 inline void setPixel(GLint x,GLint y) { glBegin(GL_POINTS); glVertex2i(x,y); glEnd(); } void drawOneLine(GLint x1,GLint y1,GLint x2,GLint y2) { if(x20.0) { p=2*dy-dx; while(x=1的情况 if(k>=1.0) { p=dy; while(yk>-1的情况 if(k>-1&&k<0) { p=2*dy+dx; while(x=0) p+=twoDy; else { y--; p+=twoSum; } setPixel(x,y); } } //k<-1的情况 if(k<=-1) { p=2*dx-dy; while(y>y2) { y--; if(p>=0) p-=twoDx; else { x++; p-=twoSum; } setPixel(x,y); } } } // void display() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0,0.0,0.0); drawOneLine(160,0,640,180); //斜率小于1 drawOneLine(480,0,0,180); //斜率在-1到0之间 drawOneLine(240,0,400,480); //斜率大于1 drawOneLine(400,0,240,480); //斜率小于-1 drawOneLine(320,0,320,480); //平行y轴 drawOneLine(0,240,640,240); //平行x轴 glFlush(); } int main(int argc,char** argv) { glutInit(&argc,argv); glutInitWindowPosition(100,100); glutInitWindowSize(winWidth,winHeight); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutCreateWindow("my app"); init(); glutDisplayFunc(display); glutMainLoop(); return 0; }