IOS - arranging subzones in circular form

I have a bunch of views in my application. I would like to arrange them in a circular form and change their center depending on the number of submissions.

So, if there are 3 types, they will look like a triangle, but still form a circle. If there are 4 of them, it will look like a square, but it will still form a circle, etc.

In short, the centers of all representations will sit on an imaginary circle.

Any suggestions?

+5
source share
3 answers

This is the code I used in one of my projects, hope this helps.

// you must set both of these
CGPoint centerOfCircle;
float radius;

int count = 0;
float angleStep = 2.0f * M_PI / [arrayOfViews count];

for (UIView *view in arrayOfViews) {
    float xPos = cosf(angleStep * count) * radius;
    float yPos = sinf(angleStep * count) * radius;
    view.center = CGPointMake(centerOfCircle.x + xPos, centerOfCircle.y +yPos);
    count++;
}
+13
source

(360 2π ) , , .

, :

// These calculate the x and y offset from the center by using the angle in radians
#define LengthDir_X(__Length__,__Direction__) (cos(__Direction__)*__Length__)
#define LengthDir_Y(__Length__,__Direction__) (sin(__Direction__)*__Length__)

// I use this to convert degrees to radians and back if I have to
#define DegToRad(__ANGLE__) (((__ANGLE__) * 2.0 * M_PI) / 360.0)
#define RadToDeg(__ANGLE__) (((__ANGLE__) * 360) / (2.0 * M_PI))
0

Here's the Swift 3 version of the accepted answer, as a UIView extension with offset arguments:

public extension UIView {
  public func distributeSubviewsInACircle(xOffset: CGFloat, yOffset: CGFloat) {
      let center = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
      let radius: CGFloat = self.bounds.size.width / 2
      let angleStep: CGFloat = 2 * CGFloat(Double.pi) / CGFloat(self.subviews.count)
      var count = 0
      for subview in self.subviews {
          let xPos = center.x + CGFloat(cosf(Float(angleStep) * Float(count))) * (radius - xOffset)
          let yPos = center.y + CGFloat(sinf(Float(angleStep) * Float(count))) * (radius - yOffset)
          subview.center = CGPoint(x: xPos, y: yPos)
          count += 1
      }
  }
}
0
source

All Articles