Skip to content

Instantly share code, notes, and snippets.

@tomasen
Last active December 25, 2021 16:59
Show Gist options
  • Save tomasen/1a9165a03eced5181b7d1074f8359b80 to your computer and use it in GitHub Desktop.
Save tomasen/1a9165a03eced5181b7d1074f8359b80 to your computer and use it in GitHub Desktop.
calcPositions for WordCloudView
func checkIntersects(rect: CGRect, rects: [CGRect]) -> Bool {
for r in rects {
if rect.intersects(r) {
return true
}
}
return false
}
func checkOutsideBoundry(canvasSize: CGSize, rect: CGRect) -> Bool {
if rect.maxY > canvasRect.height/2 {
return true
}
if rect.minY < -canvasRect.height/2 {
return true
}
return false
}
func calcPositions(canvasSize: CGSize, itemSizes: [CGSize]) -> [CGPoint] {
var pos = [CGPoint](repeating: CGPoint.zero, count: itemSizes.count)
if canvasSize.height == 0 {
return pos
}
var rects = [CGRect]()
var step : CGFloat = 0
let ratio = canvasSize.width * 1.5 / canvasSize.height
let startPos = CGPoint(x: CGFloat.random(in: 0...1) * canvasSize.width * 0.1,
y: CGFloat.random(in: 0...1) * canvasSize.height * 0.1)
for (index, itemSize) in itemSizes.enumerated() {
var nextRect = CGRect(origin: CGPoint(x: startPos.x - itemSize.width/2,
y: startPos.y - itemSize.height/2),
size: itemSize)
if index > 0 {
while checkOutsideBoundry(canvasSize: canvasSize,
rect: nextRect)
|| checkIntersects(rect: nextRect, rects: rects) {
nextRect.origin.x = startPos.x + ratio * step * cos(step) + startPos.x - itemSize.width/2
nextRect.origin.y = startPos.y + step * sin(step) + startPos.y - itemSize.height/2
step = step + 0.01
}
}
pos[index] = nextRect.center
rects.append(nextRect)
}
return pos
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment