要解决不让UIImageViews与随机的CGPoint相交的问题,可以使用以下方法:
确定UIImageView的位置和大小:首先,确定每个UIImageView的frame或bounds,以便计算出它们的位置和大小。
生成随机CGPoint:使用arc4random_uniform函数生成一个随机的CGPoint。确保CGPoint的范围不与任何UIImageView的frame相交。
检查相交:使用CGRectIntersectsRect函数检查生成的随机CGPoint是否与任何其他UIImageView的frame相交。如果相交,则返回第2步并重新生成随机CGPoint。
下面是一个示例代码,演示了如何实现上述解决方法:
func generateRandomCGPoint(forImageViews imageViews: [UIImageView], inView containerView: UIView) -> CGPoint {
var randomPoint: CGPoint
repeat {
let minX = containerView.bounds.origin.x
let minY = containerView.bounds.origin.y
let maxX = containerView.bounds.size.width
let maxY = containerView.bounds.size.height
randomPoint = CGPoint(x: minX + CGFloat(arc4random_uniform(UInt32(maxX))), y: minY + CGFloat(arc4random_uniform(UInt32(maxY))))
} while intersects(withImageViews: imageViews, atPoint: randomPoint)
return randomPoint
}
func intersects(withImageViews imageViews: [UIImageView], atPoint point: CGPoint) -> Bool {
for imageView in imageViews {
if imageView.frame.contains(point) {
return true
}
}
return false
}
// 使用示例
let imageView1 = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let imageView2 = UIImageView(frame: CGRect(x: 200, y: 200, width: 100, height: 100))
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
let imageViews = [imageView1, imageView2]
containerView.addSubview(imageView1)
containerView.addSubview(imageView2)
let randomPoint = generateRandomCGPoint(forImageViews: imageViews, inView: containerView)
print(randomPoint)
在上面的示例中,我们首先创建了两个UIImageView和一个包含它们的容器UIView。然后,我们使用generateRandomCGPoint函数生成一个不与UIImageView相交的随机CGPoint,并将其打印出来。generateRandomCGPoint函数会循环生成随机CGPoint,直到找到一个不与任何UIImageView相交的点为止。