## 中点Bresenham画圆

2010-12-04 20:53  风恋残雪  阅读(763)  评论(0编辑  收藏  举报

(1) 输入圆的半径R。

(2) 计算初始值d = 1 - R, x  = 0; y = R。

(3) 绘制点(x, y)， 及其在八分圆中的另外7个对称点。

(4) 判断d的符号，若d < 0, 则先将d更新为d+2*x+3，再将(x,y)更新为(x+1, y)，否则将d更新为d+2*(x - y) + 5，再将(x, y)更新为(x+1, y-1)。

(5) 当x <= y时，重复步骤(3)和(4)，否则结束。

#include <GL/freeglut.h>
void init (void)
{
glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
}

void drawCircle (int radius, int x1, int y1)
{
glPushMatrix ();
glTranslatef ((GLfloat) x1, (GLfloat) y1, 0.0f);
int x, y, d;
x = 0;
glBegin (GL_POINTS);
while (x <= y)
{
glVertex2i ( x,  y);
glVertex2i (-x,  y);
glVertex2i (-x, -y);
glVertex2i ( x, -y);
glVertex2i ( y,  x);
glVertex2i (-y,  x);
glVertex2i (-y, -x);
glVertex2i ( y, -x);
if (d < 0)
{
d += (x<<1) + 3;
}
else
{
-- y;
d += ((x - y)<<1) + 5;
}
++ x;
}
glEnd ();
glPopMatrix ();
}

void display (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0f, 0.0f, 0.0f);
drawCircle (200, 200, 200);
glutSwapBuffers ();
}

void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
if (w <= h)
{
gluOrtho2D (-600.0, 600.0, -600.0 * (GLfloat) h / (GLfloat) w, 600.0 * (GLfloat) h / (GLfloat) w);
}
else
{
gluOrtho2D (-600.0 * (GLfloat) w / (GLfloat) h,600.0 * (GLfloat) w / (GLfloat) h, -600.0, 600.0);
}
glMatrixMode (GL_MODELVIEW);
}
void keyboard (unsigned char key, int x, int y)
{
switch (key)
{
case 27: // 'VK_ESCAPE'
exit (0);
break;
default:
break;
}
}
int main (int argc, char ** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (600, 600);
glutCreateWindow ("Bresenham line");
init ();
glutReshapeFunc (reshape);
glutDisplayFunc (display);
glutKeyboardFunc (keyboard);
glutMainLoop ();
return 0;
}