gpt4 book ai didi

ios - CGRectIntersectsRect 用于多个 CGRect

转载 作者:行者123 更新时间:2023-11-28 22:12:28 24 4
gpt4 key购买 nike

我有 8 个 UIImageView,它们必须随机放置。我为每个 imageView 生成一个随机的 x,y pos,然后我需要检查是否有任何 imageViews 相交。如果它们相交,它会再次计算随机 x,y 位置(do..while 循环)。现在我知道的唯一方法是CGRectIntersectsRect,它只能比较2个CGRect。有没有一种方法可以检查所有这些 imageViews 是否立即相交(在 while 条件内)?

这是我已经为 3 张图片计算出的结果-

 do {

xpos1 = 60 + arc4random() % (960 - 60 + 1);
ypos1 = 147 + arc4random() % (577 - 147 + 1);



xpos2 = 60 + arc4random() % (960 - 60 + 1);
ypos2 = 147 + arc4random() % (577 - 147 + 1);



xpos3 = 60 + arc4random() % (960 - 60 + 1);
ypos3 = 147 + arc4random() % (577 - 147 + 1);

} while (CGRectIntersectsRect(CGRectMake(xpos1, ypos1,120, 120), CGRectMake(xpos2, ypos2,120, 120)) || CGRectIntersectsRect(CGRectMake(xpos2, ypos2,120,120), CGRectMake(xpos3, ypos3, 120, 120)) || CGRectIntersectsRect(CGRectMake(xpos1, ypos1,120,120), CGRectMake(xpos3, ypos3, 120, 120)) );

image1.center=CGPointMake(xpos1, ypos1);
image2.center=CGPointMake(xpos2, ypos2);
image3.center=CGPointMake(xpos3, ypos3);

最佳答案

一个简单的算法是从一个矩形开始,然后迭代地寻找新的矩形与之前的任何一个都不相交:

int numRects = 8;
CGFloat xmin = 60, xmax = 960, ymin = 147, ymax = 577;
CGFloat width = 120, height = 120;
CGRect rects[numRects];

for (int i = 0; i < numRects; i++) {
bool intersects;
do {
// Create random rect:
CGFloat x = xmin + arc4random_uniform(xmax - xmin + 1);
CGFloat y = ymin + arc4random_uniform(ymax - ymin + 1);
rects[i] = CGRectMake(x, y, width, height);

// Check if it intersects with one of the previous rects:
intersects = false;
for (int j = 0; j < i; j++) {
if (CGRectIntersectsRect(rects[i], rects[j])) {
intersects = true;
break;
}
}

// repeat until new rect does not intersect with previous rects:
} while (intersects);
}

这应该可以回答您的问题(“如何检查与多个矩形的交集”),但请注意,这种方法并不完美。如果矩形将填充“大部分”可用空间和第一个矩形放置“很糟糕”那么算法可能不会终止,因为它在某个时候找不到可接受的矩形。

我认为您的案例中使用的尺寸不会发生这种情况,但您可以保留它心里。一个可能的解决方案是计算尝试的次数,如果这比从头开始花费的时间太长。

此外,如果您必须创建许多 矩形,那么内部循环(检查intersection) 可以通过对矩形进行排序来改进,因此需要进行的比较更少制作。

关于ios - CGRectIntersectsRect 用于多个 CGRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22553601/

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