I am trying to pack a bunch of round UIViews in a hexagonal pattern. They all have different sizes.
First I randomly generate the UIViews and put them on the screen as shown:
Then I have an algorithm that arranges the views in a circular pattern around the center. This is the algorithm:
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
}
}
Here is my result after I run this function:
Now this algorithm is for circles (views) with the same size. You see that they don't lie next to each other as they would if they all had the same size. As shown here:
Is there anyone out there that has any form of clue as to what I could change in the algorithm so I can pack views with different sizes?
Here are some links that I've encountered during my research, but they haven't gotten me very far because Maths isn't my strongest side:
http://www.optimization-online.org/DB_FILE/2008/06/1999.pdf
Packing different sized circles into rectangle - d3.js
http://jsfiddle.net/TDzVE/
Thank you in advance and happy programming!