实验3 生成圆弧的中点算法
1. 算法思想
如果我们构造函数 F(x,y)=x2+y2-R2,则对于圆上的点有F(x,y)=0,对于圆外的点有F(x,y)>0,对于圆内的点F(x,y)<0 。与中点画线法一样,构造判别式:
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
我们这里讨论的第一个象素是(0,R),判别式d的初始值为:
d0=F(1,R-0.5)=1.25-R
图2 当前象素与下一象素的候选者
为了进一步提高算法的效率,将上面的算法中的浮点数改写成整数,将乘法运算改成加法运算,即仅用整数实现中点画圆法。
2. C源程序
#include<stdio.h>
#include<graphics.h>
int Center_x,Center_y,radius,color;
/**********显示圆弧的八个对称点**********/
void CirclePoints(int Center_x,int Center_y,int x,int y,int color)
{
putpixel(x+Center_x,y+Center_y,color);
putpixel(x+Center_x,-y+Center_y,color);
putpixel(y+Center_x,x+Center_y,color);
putpixel(y+Center_x,-x+Center_y,color);
putpixel(-x+Center_x,-y+Center_y,color);
putpixel(-x+Center_x,y+Center_y,color);
putpixel(-y+Center_x,-x+Center_y,color);
putpixel(-y+Center_x,x+Center_y,color);
}
/**********消除的乘法的中点算法**********/
void MidPointCircle(int Center_x,int Center_y,int radius,int color)
{
int x,y;
int d;
int DeltaE,DeltaSE;
x=0;
y=radius;
d=5-4*radius;
DeltaE=12;
DeltaSE=20-8*radius;
putpixel(Center_x,Center_y,color);
CirclePoints(Center_x,Center_y,x,y,color);
while(y>x)
{
if(d<=0)
{
d+=DeltaE;
DeltaSE+=8;
}
else
{
d+=DeltaSE;
DeltaSE+=16;
y--;
}
DeltaE+=8;
x++;
CirclePoints(Center_x,Center_y,x,y,color);
}
}
/**********主函数**********/
void main( )
{
int graphdriver=DETECT,graphmode;
initgraph(&graphdriver,&graphmode,"\\tc");
printf("************************************************************\n");
printf("* Middle-Point Algorithm for Circling *\n");
printf("* Creator:Zhang Zujin *\n");
printf("* *\n");
printf("* Input: Center and Radius of Circle and Color Index *\n");
printf("* Output: The Circle Related to Input *\n");
printf("************************************************************\n\n");
printf("Please Input Center Coordinate(x,y):");
scanf("%d%d",&Center_x,&Center_y);
printf("Please Input Radius:");
scanf("%d",&radius);
printf("Input Color Index[0,15]:");
scanf("%d",&color);
MidPointCircle(Center_x,Center_y,radius,color);
getch( );
closegraph( );
}