简体   繁体   中英

Calculate center coordinate of Subview on a circle in a UIView (inverted coordinate system)

I'd like to position the center of a UIButton/UIView (red dot) on the border of a imaginary circle as Subview of another UIView – This means the coordinate system is inverted.

在此处输入图片说明

How do I calculate the CGPoint for the red box center on the circle. Here is what I have …

  • (CGPoint) circleCenter x,y
  • (float) circleRadius r
  • (float) angleAsRadian ⍺

here's what I am trying (thanks @rmaddy)

CGFloat buttonX = circleCenter.x + cos(angleAsRadian) * radius;
CGFloat buttonY = circleCenter.y - sin(angleAsRadian) * radius;

CGPoint buttonCenter = CGPointMake(buttonX, buttonY);

UIButton* buttonMarker = [[UIButton alloc]initWithFrame:CGRectMake(0,0, 20, 20)];
[buttonMarker addTarget:self action:@selector(showTitle:) forControlEvents:UIControlEventTouchUpInside];
[buttonMarker setBackgroundColor:[UIColor greenColor]];
[buttonMarker setCenter:buttonCenter];
[_view addSubview:buttonMarker];

... and the current result:

在此处输入图片说明

I am actually expecting the green buttons them to be positioned on top of the pink circles. So not quite there, yet.

Values:

  • Radian 10.995574
  • Radian 12.042772

Import <math.h> and do:

CGPoint circle = ... // the center of the circle
CGFloat angle = ... // the angle in radians
CGFloat radius = ...// the radius

CGFloat buttonX = circle.x + cos(angle) * radius;
CGFloat buttonY = circle.y - sin(angle) * radius;

CGPoint buttonCenter = CGPointMake(buttonX, buttonY);

If you have the angle in degrees you need to convert it to radians.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM