开发环境:
VC++6.0,OpenGL
实验内容:
使用中点Bresenham算法画椭圆。
实验结果:
代码:
1 #include <gl/glut.h> 2 3 #define WIDTH 500 4 #define HEIGHT 500 5 #define OFFSET 15 //偏移量,偏移到原点 6 #define A 6 7 #define B 5 8 9 void Init() //其它初始化 10 { 11 glClearColor(1.0f,1.0f,1.0f,1.0f); //设置背景颜色,完全不透明 12 glColor3f(1.0f,0.0f,0.0f); //设置画笔颜色 13 14 glMatrixMode(GL_PROJECTION); 15 glLoadIdentity(); 16 gluOrtho2D(0.0, 30.0, 0.0, 30.0); 17 glMatrixMode(GL_MODELVIEW); 18 } 19 20 void MidBresenhamEllipse(int a,int b) //中点Bresenham算法画椭圆 21 { 22 int x,y; 23 float d1,d2; 24 x = 0;y = b; 25 d1=b*b+a*a*(-b+0.25); 26 glPointSize(5); //设置画笔尺寸 27 28 glBegin(GL_POINTS); 29 glVertex2i(OFFSET+x,OFFSET+y); 30 glVertex2i(OFFSET-x,OFFSET-y); 31 glVertex2i(OFFSET-x,OFFSET+y); 32 glVertex2i(OFFSET+x,OFFSET-y); 33 glEnd(); 34 35 while(b*b*(x+1) < a*a*(y-0.5)){ 36 if(d1<=0){ 37 d1+=b*b*(2*x+3); 38 x++; 39 } 40 else{ 41 d1+=b*b*(2*x+3)+a*a*(-2*y+2); 42 x++; 43 y--; 44 } 45 glBegin(GL_POINTS); 46 glVertex2i(OFFSET+x,OFFSET+y); 47 glVertex2i(OFFSET-x,OFFSET-y); 48 glVertex2i(OFFSET-x,OFFSET+y); 49 glVertex2i(OFFSET+x,OFFSET-y); 50 glEnd(); 51 }//while上半部分 52 d2=b*b*(x+0.5)*(x+0.5)+a*a*(y-1)*(y-1)-a*a*b*b; 53 while(y>0){ 54 if(d2<=0){ 55 d2+=b*b*(2*x+2)+a*a*(-2*y+3); 56 x++,y--; 57 } 58 else{ 59 d2+=a*a*(-2*y+3); 60 y--; 61 } 62 glBegin(GL_POINTS); 63 glVertex2i(OFFSET+x,OFFSET+y); 64 glVertex2i(OFFSET-x,OFFSET-y); 65 glVertex2i(OFFSET-x,OFFSET+y); 66 glVertex2i(OFFSET+x,OFFSET-y); 67 glEnd(); 68 } 69 } 70 71 void Display() 72 { 73 glClear(GL_COLOR_BUFFER_BIT); //清空颜色堆栈 74 75 MidBresenhamEllipse(A,B); //画一个半径为8的椭圆 76 77 glFlush(); //清空缓冲区指令 78 } 79 80 int main(int argc,char** argv) 81 { 82 glutInit(&argc,argv); 83 glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); //初始化显示模式 84 glutInitWindowSize(WIDTH,HEIGHT); //初始化窗口大小 85 glutInitWindowPosition(200,100); //初始化窗口出现位置 86 glutCreateWindow("中点Bresenham画椭圆"); //初始化窗口标题 87 88 glutDisplayFunc(Display); //注册显示函数 89 Init(); //其它初始化 90 glutMainLoop(); //进入程序循环 91 92 return 0; 93 }
Freecode : www.cnblogs.com/yym2013
时间: 2024-10-06 01:09:52