Skawful
Skawful

Reputation: 9897

Help drawing circle in iPhone

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);

Upvotes: 0

Views: 6979

Answers (3)

Groumfy69
Groumfy69

Reputation: 51

You only need 2 lines of code to draw a real round circle. My sample code:

CGContextAddArc(contextRef,centerX,centerY,radius,0,2*3.1415926535898,1);
CGContextDrawPath(contextRef,kCGPathStroke);

Upvotes: 5

Vladimir
Vladimir

Reputation: 170839

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));

Upvotes: 7

Matthew Chen
Matthew Chen

Reputation: 209

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

Upvotes: 0

Related Questions