橢圓可以看成是圓的一種特殊情況
下面介紹中點畫橢圓算法,具體的數學推導過程以後補上或者大家可以參考任何一本計算機圖形學的書籍都會有推導的過程,直接上代碼,我認爲效果不是特別的好
#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;
}