# 【计算机图形学】基本图形元素：圆的生成算法

08年9月入学，12年7月毕业，结束了我在软件学院愉快丰富的大学生活。此系列是对四年专业课程学习的回顾，索引参见：http://blog.csdn.net/xiaowei_cqu/article/details/7747205

# 圆的特征

void CirclePoints(int x,int y,int color)
{ Putpixel(x,y,color); Putpixel(y,x,color);
Putpixel(-x,y,color); Putpixel(y,-x,color);
Putpixel(x,-y,color); Putpixel(-y,x,color);
Putpixel(-x,-y,color); Putpixel(-y,-x,color);
}


# 中点画圆算法

d=F(M)=F(xp+1,yp-0.5)=(xp+1)2+(yp-0.5)2-R2
若 d<0，则应取P1为下一象素，而且再下一象素的判别式为：
d=F(xp+2,yp-0.5)=(xp+2)2+(yp-0.5)2-R2=d+2xp+3
若d≥0，则应取P2为下一象素，而且下一象素的判别式为
d=F(xp+2,yp-1.5)=(xp+2)2+(yp-1.5)2-R2=d+2(xp-yp)+5

d0=F(1,R-0.5)=1.25-R

## 【算法代码】

void PaintArea::drawCircleMiddle(QPainter &painter,const QPoint ¢er, int r)
{
int x,y,deltax,deltay,d;
x=0;y=r;
deltax=3;deltay=2-3-3;d=1-r;
while(x<y)
{
if(d<0)
{
d+=deltax;
deltax+=2;
x++;
}
else
{
d+=(deltax+deltay);
deltax+=2;deltay+=2;
x++;y++;
}
painter.drawPoint(center.x()+x,center.y()+y);
painter.drawPoint(center.x()+x,center.y()-y);
painter.drawPoint(center.x()-x,center.y()+y);
painter.drawPoint(center.x()-x,center.y()-y);
painter.drawPoint(center.x()+y,center.y()+x);
painter.drawPoint(center.x()+y,center.y()-x);
painter.drawPoint(center.x()-y,center.y()+x);
painter.drawPoint(center.x()-y,center.y()-x);
}
}


# Bresenham画圆算法

## 【算法代码】

void PaintArea::drawCircleBresenham(QPainter &painter,const QPoint ¢er, int r)
{
int x,y,delta,delta1,delta2,direction;
x=0;y=r;
delta=2*(1-r);
while(y>=0)
{
painter.drawPoint(x,y);
if(delta<0)
{   delta1=2*(delta+y)-1;
if(delta1<=0)direction=1; else direction=2; }
else if(delta>0)
{   delta2=2*(delta-x)-1;
if(delta2<=0)direction=2; else direction=3; }
else  direction=2;
switch(direction)
{case 1:
x++;delta+=2*x+1; break;
case 2:
x++; y--; delta+=2*(x-y+1); break;
case 3:
y--;delta+=(-2*y+1); break;
}
}
}


# 椭圆弧生成算法

## 【算法代码】

void PaintArea::drawEllipseMiddle(QPainter &painter,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,x=0,y=Ry,px=0,py=twoRx2*y;
void ellipsePlotPoints(QPainter&,int,int,int,int);
ellipsePlotPoints(painter,xCenter,yCenter,x,y);
//Region1
p=round(Ry-(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(painter,xCenter,yCenter,x,y);
}
//Region2
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;
}
ellipsePlotPoints(painter,xCenter,yCenter,x,y);
}
}
void ellipsePlotPoints(QPainter &painter,int xCenter,int yCenter,int x,int y)
{    painter.drawPoint(xCenter+x,yCenter+y);
painter.drawPoint(xCenter-x,yCenter+y);
painter.drawPoint(xCenter+x,yCenter-y);
painter.drawPoint(xCenter-x,yCenter-y);
}