OpenGL学习之中点画圆算法

来源:互联网 发布:java正则表达式非数字 编辑:IT博客网 时间:2019/07/20 17:55

中点画圆算法

在每个布中以单位间隔取样并确定离指定圆最近的像素位置。

代码如下:

#include <gl/glut.h>class screenpt{private:GLint x,y;public:screenpt(){x = y = 0;}void setcoords(GLint xcoord,GLint ycoords){x = xcoord;y = ycoords;}GLint getx() const{return x;}GLint gety() const{return y;}void incrementx(){x++;}void incrementy(){y++;}void decrementx(){x--;}void decreamenty(){y--;}};void  setpixel(GLint xcoord,GLint ycoord){glPointSize(5);glBegin(GL_POINTS);glVertex2i(xcoord,ycoord);glEnd();}void circlePlotPoints(GLint xc,GLint yc,screenpt circpt){setpixel(xc+circpt.getx(),yc+circpt.gety());setpixel(xc+circpt.getx(),yc-circpt.gety());setpixel(xc-circpt.getx(),yc+circpt.gety());setpixel(xc-circpt.getx(),yc-circpt.gety());setpixel(xc+circpt.gety(),yc+circpt.getx());setpixel(xc-circpt.gety(),yc+circpt.getx());setpixel(xc+circpt.gety(),yc-circpt.getx());setpixel(xc-circpt.gety(),yc-circpt.getx());}void circleMIDpoint(GLint xc,GLint yc,GLint radius){screenpt cirpt;GLint p =1-radius;cirpt.setcoords(0,radius);circlePlotPoints(xc,yc,cirpt);while(cirpt.getx()<cirpt.gety()){cirpt.incrementx();if(p<0){p += 2*cirpt.getx() + 1;}else{cirpt.decreamenty();p += 2*(cirpt.getx()-cirpt.gety()) + 1;}circlePlotPoints(xc,yc,cirpt);}}void init(){glClearColor(1.0,1.0,1.0,0.0);glMatrixMode(GL_PROJECTION);gluOrtho2D(-10,10,-10,10);}void display(){glClear(GL_COLOR_BUFFER_BIT);glColor3f(0.0,0.0,1.0);circleMIDpoint(1,1,5);glFlush();}int main(int argc,char **argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("hello");init();glutDisplayFunc(display);glutMainLoop();return 0;}

画出来的效果其实并不是特别的好


看完上面的中点画圆算法之后我们看看利用极坐标画圆的结果,

因为极坐标的坐标表示为x = cos(theta),y  = sin(theta)

那么很显然就可以使用下面的程序进行画图了,看程序

#include <gl/glut.h>#include <stdlib.h>#include <stdio.h>#include <math.h>#define PI 3.14159f#define R 5GLfloat theta = 0.0f;#define n 100void init(){glClearColor(0.0,0.0,0.0,0.0);glColor3f(1.0,1.0,0.0);glMatrixMode(GL_PROJECTION);gluOrtho2D(-10,10,-10,10);}void display(){//GLfloat x,y;glClear(GL_COLOR_BUFFER_BIT);glColor3f(1.0,0.0,0.0);glPointSize(5);glBegin(GL_POINTS);for(int i=0;i<n;i++)glVertex2f(R*cos(2*PI/n*i),R*sin(2*PI/n*i));glEnd();glFlush();}int main(int argc,char **argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(500,500);glutInitWindowPosition(0,0);glutCreateWindow("hello");init();glutDisplayFunc(display);glutMainLoop();return 0;}

0 0
原创粉丝点击