Thursday, April 14, 2011

C implementation of Midpoint Ellipse Drawing Algorithm

Hi friends ,this time I am posting a program for Midpoint Ellipse Drawing Algorithm in C implemented during my Computer Graphics studies.Note that the output or screenshot shown is REAL and taken using a Virtual Machine.Program written is very simple and can be understood easily.Anyways do leave a comment to us if you got any queries .

PROGRAM CODE
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
int gdriver=DETECT, gmode,i,x,y;
void main()
{
long d1,d2,rx,ry,rxsq,rysq,trxsq,trysq,dx,dy;
printf("\nPlease enter the x radius of the ellipse\n");
scanf("%ld",&rx);
printf("Please enter the y radius of the ellipse\n");
scanf("%ld",&ry);
initgraph(&gdriver,&gmode,"c:\\tc\\bgi");
int xmid,ymid;
xmid=getmaxx()/2;
ymid=getmaxy()/2;
line(xmid+rx+10,ymid-ry,xmid+rx+10,ymid);
line(xmid,ymid-ry-10,xmid+rx,ymid-ry-10);
char ch[20];
sprintf(ch,"%c",17);
outtextxy(xmid,ymid-ry-13,ch);
sprintf(ch,"%c",16);
outtextxy(xmid+rx-6,ymid-ry-13,ch);
sprintf(ch,"%c",30);
outtextxy(xmid+rx+7,ymid-ry,ch);
sprintf(ch,"%c",31);
outtextxy(xmid+rx+7,ymid-6,ch);
sprintf(ch,"%d",rx);
outtextxy(xmid+(rx/2)-5,ymid-ry-20,ch);
sprintf(ch,"%d",ry);
outtextxy(xmid+rx+20,ymid-(ry/2)-1,ch);
outtextxy(getmaxx()-450,getmaxy()-20,"MidPoint Ellipse Algorithm :Program By 1st Kinecteers");
rectangle(getmaxx()-455,getmaxy()-25,getmaxx()-30,getmaxy()-7);
rxsq=rx*rx;
rysq=ry*ry;
trxsq=2*rxsq;
trysq=2*rysq;
x=0;
y=ry;
d1=rysq-rxsq*ry+(0.25*rxsq);
dx=trysq*x;
dy=trxsq*y;
do
{
putpixel(xmid+x,ymid+y,15);
putpixel(xmid-x,ymid-y,15);
putpixel(xmid+x,ymid-y,15);
putpixel(xmid-x,ymid+y,15);
if(d1<0){
x=x+1;
y=y;
dx=dx+trysq;
d1=d1+dx+rysq;
}
else{
x=x+1;
y=y-1;
dx=dx+trysq;
dy=dy-trxsq;
d1=d1+dx-dy+rysq;
}}
while(dx<dy);
d2=rysq*(x+0.5)*(x+0.5)+rxsq*(y-1)*(y-1)-rxsq*rysq;
do
{
putpixel(xmid+x,ymid+y,15);
putpixel(xmid-x,ymid-y,15);
putpixel(xmid+x,ymid-y,15);
putpixel(xmid-x,ymid+y,15);
if(d2>0){
x=x;
y=y-1;
dy=dy-trxsq;
d2=d2-dy+rxsq;
}
else{
x=x+1;
y=y-1;
dy=dy-trxsq;
dx=dx+trysq;
d2=d2+dx-dy+rxsq;
}}
while(y>0);
getch();
}
OUTPUT: