gpt4 book ai didi

ios - 如何防止 UIViews 接触

转载 作者:行者123 更新时间:2023-11-28 15:31:43 28 4
gpt4 key购买 nike

所以我在屏幕中央有一个 150 x 150 的主 Imageview,我以编程方式创建具有随机 x 和 y 值以及随机宽度/高度(这些值相同)的 View 。我希望 View 围绕主 ImageView 但不要触摸它。同样在 y 轴上,我有一个带有 self.view.frame 和高度 35 的标签栏,我也不希望这些 View 触及。有什么想法吗?

最佳答案

为什么不随机化极坐标(角度和半径,引用是 ImageView 的中心)而不是笛卡尔坐标(x 和 y)?如果您有角度和半径,将更容易控制距中心的距离。您可以根据最终的随机宽度和高度增加半径,使其离中心更远,以进行补偿并避免碰撞。

let centerImageView = UIImageView()

//..

//Bounding circle for the image view
let centerRadius = max(centerImageView.width, centerImageView.height)

func randomFloat(min: Float, max: Float) {
return min + (max - min) * (arc4random() / RAND_MAX)
}

//Somewhere else in your loop for generating views

let angle = randomFloat(0, Float.pi * 2)
//Dimensions of the random view
let width = randomFloat(min: 10, max: 50)
let height = randomFloat(min: 10, max: 50)
//Bounding circle, you can use an ellipse, or calculate the distance perfectly for that angle too, but this is simpler
let viewRadius = randomFloat(min: width, max: height)
//The distance from the center must be greater than the sum of both bounding circles' radiuses, plus some
let radius = centerRadius + viewRadius + randomFloat(min: 50, max: 100)
//Convert to cartesian coordinates
let x = centerImageView.center.x + cos(angle) * radius
let y = centerImageView.center.y + sin(angle) * radius

let view = UIView(frame: CGRect(x: x, y: y, width: width, height: height)

enter image description here

关于ios - 如何防止 UIViews 接触,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663106/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com