2016-11-17 58 views
1

我正在嘗試在六角形模式中包裝一堆圓UIViews。 它們都有不同的尺寸。如何在iOS中爲不等大小的圓圈創建圓圈包裝算法?

首先我隨機生成的UIViews,並把它們在屏幕上,如下所示: enter image description here
然後我有安排在圍繞中心的圓形圖案的視圖的算法。這是算法:

func arrangeViews() 
    { 
     let viewCenter = self.view.center 
     let radius: Double = 50?? <- What do I put here? All the views has different radius? 
     var currentDistFromCenter: Double = (radius * 2) 
     var numMoved = 0 
     let amountOfViews = views.count 

     numMoved += 1 

     while numMoved < amountOfViews { 
      var numberToFit = Double(M_PI/asin(radius/currentDistFromCenter)) 

      if numberToFit > Double(amountOfViews - numMoved) { 
       numberToFit = Double(amountOfViews - numMoved) 
      } 

      for i in 0 ..< Int(numberToFit) { 
       let currentView = views[numMoved] 
       let angle = Double(M_PI * 2.0 * Double(i)/numberToFit) 
       let x = Double(viewCenter.x) + cos(angle) * currentDistFromCenter 
       let y = Double(viewCenter.y) + sin(angle) * currentDistFromCenter 
       var newPoint = CGPoint(x: CGFloat(x), y: CGFloat(y)) 

       views.first?.center = self.view.center 

       if newPoint.x != currentView.frame.origin.x || newPoint.y != currentView.frame.origin.y { 
        UIView.animate(withDuration: 0.3, animations: { 
         currentView.center = newPoint 
        }) 
        numMoved += 1 
       } 
      } 
      currentDistFromCenter += radius * 2 
     } 
    } 

這裏是我的結果,我跑這個功能後:
enter image description here
現在,這個算法是圈(視圖)具有相同的大小。你會發現它們並不像彼此相鄰,就好像它們都具有相同的尺寸一樣。如圖所示: enter image description here

有沒有人在那裏,有任何形式的線索,以什麼我可以在算法改變,所以我可以包不同大小的看法?

這裏是我的研究過程中,我遇到了一些聯繫,但他們沒有得到我很遠,因爲數學是不是我的最強的一面:
http://www.optimization-online.org/DB_FILE/2008/06/1999.pdf
Packing different sized circles into rectangle - d3.js
http://jsfiddle.net/TDzVE/


預先感謝您和開心編程!

回答

0

根據所需的結果,我寧願先畫出同一中心的所有7個圓圈。

假設red colored center circle is of size (x, y, W, H)

然後

1st (Top left)   - (x-W/2, y-(H+H/2), W, H) 
2nd (Top right)  - (x+W/2, y-(H+H/2), W, H) 
3rd (Right)   - (x+W, y, W, H) 
4th (Bottom right)  - (x+W/2, y+(H+H/2), W, H) 
5th (Bottom left)  - (x-W/2, y+(H+H/2), W, H) 
6th (Left)    - (x-W, y, W, H) 

這將在六邊形部分的所有的情況下被應用,只要W/H將每個圓圈改變像

1st (Top left)   - (x-W/2, y-(H+H/2), W1, H1) 
2nd (Top right)  - (x+W/2, y-(H+H/2), W2, H2) 
3rd (Right)   - (x+W, y, W3, H3) 
4th (Bottom right)  - (x+W/2, y+(H+H/2), W4, H4) 
5th (Bottom left)  - (x-W/2, y+(H+H/2), W5, H5) 
6th (Left)    - (x-W, y, W6, H6)