Greg Memo
Greg Memo

Reputation: 21

Drawing a circle with Pythagorean equation

I HAVE to draw a circle with the following code (check if point is on the circle).

int rad=10;
// i=x,j=y
for (int j=ymid-rad;j<=ymid+rad;j++){
   for (int i=xmid-rad;i<=xmid+rad;i++){
      if (((i-xmid)*(i-xmid)+(j-ymid)*(j-ymid)) == rad*rad)
         Image1->Canvas->Pixels[i][j]=clRed;
   }
}

However it only draws a few points of the circle. What am I doing wrong?

Thank you.

Upvotes: 0

Views: 1921

Answers (2)

tp1
tp1

Reputation: 1207

Range based version would work like this:

bool RangeCheck(float val, float r1, float r2) {
   return val >= r1 && val <= r2;
}
bool Circle(float x, float y, float rad) {
   return RangeCheck(sqrtf(x*x+y*y), rad-0.8, rad+0.8);
}
bool CircleWithCenter(float x, float y, float cx, float cy, float rad) {
   x-=cx; y-=cy;
   return Circle(x,y,rad);
}

This kind of range is how they can draw isolines in weather forecasts, but works also for circles.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272447

You're doing all of this in integer arithmetic; there are very few integer solutions to x^2 + y^2 == r^2 (for a fixed r).

I suggest using something like the midpoint circle algorithm instead.

Upvotes: 3

Related Questions