开发者

Placing Buttons on a Circle

I'm having a heck of a time calculating points on a circle in Objective-C. Even after reading TONS of other code samples my circle is still way off center. (And that's taking into consideration "center" vs "origin" and adjusting for the size of the UIView, in this case a UIButton.)

Here's the code I'm using. The circle is formed correctly, it's just off center. I'm not sure if this is a radians vs degrees problem or something else. This is a helper function in a ViewController that programmatically creates the UIButtons and adds them to the view:

- (CGPoint)pointOnCircle:(int)thisPoint withTotalPointCount:(int)totalPoints {
    CGPoint centerPoint = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
    float radius = 100开发者_如何学运维.0;
    float angle = ( 2 * M_PI / (float)totalPoints ) * (float)thisPoint;
    CGPoint newPoint;
    newPoint.x = (centerPoint.x / 2) + (radius * cosf(angle));
    newPoint.y = (centerPoint.y / 2) + (radius * sinf(angle));
    return newPoint;   
}

Thanks for the help!


The center of your buttons (i.e. points on the circle) is

newPoint.x = (centerPoint.x) + (radius * cosf(angle));  // <= removed / 2
newPoint.y = (centerPoint.y) + (radius * sinf(angle));  // <= removed / 2

Please note that if you place buttons (i.e. rectangles) on these points you have to make sure that their center lies at this point (i.e. subtract buttonWidth/2 from newPoint.x and buttonHeight/2 from newPoint.y to get the top left corner).


Not sure why you divide by 2 a second time newPoint coordinates...

What about this:

newPoint.x = centerPoint.x + (radius * cosf(angle));
newPoint.y = centerPoint.y + (radius * sinf(angle));
return newPoint;   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜