views:

58

answers:

2

The following is a snippet of code where I am trying to draw a circle but my x value prints as a constant value. It's most likely something very very simple. Thanks in advance for any help.

int sides = 100;
int radius = 200;
int centerX = 100;
int centerY = 100;
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(context, red);
CGContextBeginPath(context);


CGContextMoveToPoint(context, 0, 0);
int i = 0;
for(i = 0; i <= sides; i++)
{

    CGFloat pointRatio = i/sides;
    CGFloat xSteps = cos( pointRatio * 2 * M_PI);
    CGFloat ySteps = sin( pointRatio * 2 * M_PI );
    CGFloat pointX = centerX + xSteps * radius;
    CGFloat pointY = centerY + ySteps * radius;
    NSLog(@"%i", pointX);

    CGContextAddLineToPoint(context, pointX, pointY);
}
CGContextStrokePath(context);
+3  A: 
CGFloat pointRatio = i/sides;

When you divide 2 integers the result will be also integer - 0 in your case. You must ensure that floating point division will be performed:

CGFloat pointRatio = 1.0f*i/sides;
// Or even better
CGFloat pointRatio = i/(CGFloat)sides;

By the way why don't you want to draw circle using built-in function:

CGPathAddEllipseInRect(path, NULL, 
           CGRectMake(centerX - radius, centerY - radius, 2*radius, 2*radius));
Vladimir
You could also just convert one side of the division or the other to a floating-point type; for example, `i/(CGFloat)sides`. But yeah, `CGPathAddEllipseInRect` is the proper way to do it; plotting a hecatogon yourself is the hard way.
Peter Hosey
@Peter, is there any difference between these two ways to divide? Or compiler finally makes them the same instructions?
Vladimir
Yours is a multiplication and a division; mine is a division alone. The compiler might very well optimize out the multiplication, but I would rather not write the code for it in the first place.
Peter Hosey
The reason not to draw the circle via a built in functions is that it will eventually be a distorted line and not a perfect circle. Thanks for the great answer.
Skawful
Skawful: How will your circle become distorted? Are you repeatedly concatenating to the transformation matrix and accumulating some sort of error in it? How will plotting a hecatogon avoid this?
Peter Hosey
A: 

Previous answer is correct. Also, use cosf() and sinf(), not cos() and sin() - you're working with float precision.

Matthew Chen
“Previous answer” doesn't say much when they're all “answered Aug 05 '10”. You should refer to the answer by its author's name.
Peter Hosey
Matthew thanks, interestingly enough sin() and cos() give me enough resolution in the final drawing... would that meant that I should just use those? Or will i have problems later on doing that.
Skawful