我正在嘗試在六角形模式中包裝一堆圓UIViews。 它們都有不同的尺寸。如何在iOS中爲不等大小的圓圈創建圓圈包裝算法?
首先我隨機生成的UIViews,並把它們在屏幕上,如下所示:
然後我有安排在圍繞中心的圓形圖案的視圖的算法。這是算法:
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
}
}
這裏是我的結果,我跑這個功能後:
現在,這個算法是圈(視圖)具有相同的大小。你會發現它們並不像彼此相鄰,就好像它們都具有相同的尺寸一樣。如圖所示:
有沒有人在那裏,有任何形式的線索,以什麼我可以在算法改變,所以我可以包不同大小的看法?
這裏是我的研究過程中,我遇到了一些聯繫,但他們沒有得到我很遠,因爲數學是不是我的最強的一面:
http://www.optimization-online.org/DB_FILE/2008/06/1999.pdf
Packing different sized circles into rectangle - d3.js
http://jsfiddle.net/TDzVE/
預先感謝您和開心編程!