CG 8
CG 8
x2 + y2 = r2
y = ± sqrt(r2 - x2)
Cont…
Obviously in most of the cases the circle is
not centered at (0, 0), rather there is a center
point (xc, yc); other than (0, 0). Therefore the
equation of the circle having center at point
(xc, yc):
(x-xc)2 + (y-yc)2 =r2
Y= yc ± sqrt(r2 –(x-xc)2)
Using above equation a circle can easily be
drawn. The value of x varies from r-xc to r+xc.
and y will be calculated using above formula.
Algorithm
Circle1 (xcenter, ycenter, radius)
for x = radius - xcenter to radius + xcenter
y= yc + sqrt(r2 –(x-xc)2)
Drawpixel(x,y)
y= yc - sqrt(r2 –(x-xc)2)
Drawpixel(x,y)
#include<graphics.h>
#include<conio.h>
#include<math.h>
#include<iostream.h>
int main()
{
int d,m;
d=DETECT;
initgraph(&d,&m,"");
int x=0,y=0, r=30;
int x1=200,y1=200;
for(x=r-x1;x<=r+x1;x++)
{
y=y1+sqrt((r*r)- pow((x-x1),2));
putpixel(x,y,8);
y=y1-sqrt((r*r)- pow((x-x1),2));
putpixel(x,y,8);
}
getch();
return 0;
}
Using Cartesian coordinate inefficient
because of the multiplications and square
root operations.
It also creates large gaps in the circle.
Circle drawing using Polar
coordinates
A better approach, to draw circle using
polar coordinates r and θ.
Expressing the circle equation in
parametric polar form yields the pair of
equations
x = xc + r cos θ
y = yc + r sin θ
Using above equation circle can be plotted
by calculating x and y coordinates as θ
takes values from 0 to 360 degrees or 0 to
2π.
Circle2 (xcenter, ycenter, radius)
for θ = 0 to 2π step 1
x = xc + r * cos θ
y = yc + r * sin θ
drawPixel (x, y)
#include<graphics.h>
#include<conio.h>
#include<math.h>
#include<iostream.h>
int main()
{
int d,m;
d=DETECT;
initgraph(&d,&m,"");
int x=0,y=0, r=100;
int x1=200,y1=200;
for(double Q=0;Q<=360;++Q)///r))
{
x=x1 + round(r*cos(Q));
y=y1 + round(r*sin(Q));
putpixel(x,y,8);
}
getch();
return 0;
}
The ellipse Function
Declarations of ellipse function :-
void ellipse(int x, int y, int stangle,
int endangle, int xradius, int yradius);
Ellipse is used to draw an ellipse (x,y) are
coordinates of center of the ellipse, stangle is
the starting angle, end angle is the ending angle,
and fifth and sixth parameters specifies the X
and Y radius of the ellipse. To draw a complete
ellipse strangles and end angle should be 0 and
360 respectively
Example
#include<math.h>
#include<iostream.h>
int main()
{
int d = DETECT, m;
initgraph(&d, &m, "");
ellipse(200, 200, 0, 360, 100, 50);
getch();
closegraph();
return 0;
}
#include<graphics.h>
#include<conio.h>
main()
{
int d = DETECT,m,left=100,top=100,right=200,bottom=200,x= 300,y=150,radius=50;
getch();
closegraph();
return 0;
}