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);
CGContextMov开发者_运维问答eToPoint(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);
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));
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);
Previous answer is correct. Also, use cosf() and sinf(), not cos() and sin() - you're working with float precision.
精彩评论