【问题标题】:iOS - Arrange subviews in circular shapeiOS - 以圆形排列子视图
【发布时间】:2012-07-17 22:52:35
【问题描述】:

我的应用中有很多视图。我想将它们排列成圆形,并根据存在的视图数量改变它们的中心。

因此,如果有 3 个视图,它们看起来像一个三角形,但仍会形成一个圆圈。如果有 4 个,它看起来像一个正方形,但仍然是一个圆形,依此类推......

简而言之,所有视图的中心都位于一个假想的圆上。

有什么建议吗?

【问题讨论】:

    标签: iphone objective-c ios cocoa ipad


    【解决方案1】:

    这是我在一个项目中使用的代码,希望对您有所帮助。

    // 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++;
    }
    

    【讨论】:

      【解决方案2】:

      这是公认答案的 Swift 3 版本,作为带有偏移参数的 UIView 扩展:

      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
            }
        }
      }
      

      【讨论】:

        【解决方案3】:

        您可以将圆的度数(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))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-23
          • 2016-08-17
          • 1970-01-01
          • 2017-09-20
          • 2019-03-12
          • 1970-01-01
          相关资源
          最近更新 更多