椭圆可以看成是圆的一种特殊情况
下面介绍中点画椭圆算法,具体的数学推导过程以后补上或者大家可以参考任何一本计算机图形学的书籍都会有推导的过程,直接上代码,我认为效果不是特别的好
#include <gl/glut.h>
#include <stdio.h>
#include <math.h>
inline int round(const float a)
{
return int(a+0.5);
}
void setpixel(GLint xcoord,GLint ycoord)
{
glPointSize(5);
glBegin(GL_POINTS);
glVertex2i(xcoord,ycoord);
glEnd();
}
void ellipseplotPoints(int Xcenter,int yCenter,int x,int y)
{
setpixel(Xcenter+x,yCenter+y);
setpixel(Xcenter-x,yCenter+y);
setpixel(Xcenter+x,yCenter-y);
setpixel(Xcenter-x,yCenter-y);
}
void eclipseMidpoint(int xCenter,int yCenter,int Rx,int Ry)
{
int Rx2 = Rx*Rx;
int Ry2 = Ry*Ry;
int twoRx2 = 2*Rx2;
int twoRy2 = 2*Ry2;
int p;
int x = 0;
int y = Ry;
int px = 0;
int py = twoRx2*y;
ellipseplotPoints(xCenter,yCenter,x,y);
p = round(Ry2-(Rx2*Ry)+(0.25*Rx2));
while(px<py)
{
x++;
px += twoRy2;
if(p<0)
p += Ry2 + px;
else
{
y--;
py -= twoRx2;
p += Ry2 + px - py;
}
ellipseplotPoints(xCenter,yCenter,x,y);
}
p = round(Ry2*(x+0.5)*(x+0.5)+Rx2*(y-1)*(y-1)-Rx2*Ry2);
while(y>0)
{
y--;
py -= twoRx2;
if(p>0)
p += Rx2 - py;
else
{
x++;
px += twoRy2;
p += Rx2 -py + px;
}
eclipseMidpoint(xCenter,yCenter,x,y);
}
}
void init()
{
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-10,15,-10,15);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,1.0);
//glPointSize(5);
eclipseMidpoint(5,5,2,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;
}
利用及左边有两种情况,第一种情况,该椭圆的长短轴和坐标轴平行,那么这种情况非常的简单,只需要将画圆的方法copy过来就可以了
#include <gl/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PI 3.14159f
#define R1 5
#define R2 8
GLfloat theta = 0.0f;
#define n 100
void init()
{
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(1.0,1.0,0.0);
glMatrixMode(GL_PROJECTION);
//glLoadIdentity();
gluOrtho2D(-10,20,-10,20);
}
void display()
{
//GLfloat x,y;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2f(-10,5);
glVertex2f(20,5);
glVertex2f(5,20);
glVertex2f(5,-20);
glEnd();
glPointSize(5);
glBegin(GL_POINTS);
for(int i=0;i<n;i++)
glVertex2f(R1*cos(2*PI/n*i),R2*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;
}