代码改变世界

中点Bresenham画圆

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

这里不仔细讲原理,只是把我写的算法发出来,跟大家分享下,如果有错误的话,还请大家告诉我,如果写的不好,也请指出来,一起讨论进步。

算法步骤:

(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; 
	y = radius;
	d = 1 - radius;
	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);
	glLoadIdentity ();
	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);
	glLoadIdentity ();
	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);
	glLoadIdentity ();
}
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;
}

 

Locations of visitors to this page