CGRectIntersectsRect工作不一致

时间:2016-09-02 17:57:54

标签: ios objective-c

我有生成随机CGRect的代码,检查它是否与前一个数组中的任何其他rects相交,如果没有,则将新的rect添加到数组中。这非常好用,但我也想确保随机CGRect也不会与屏幕中心的图像重叠。我创建了一个矩形,勾勒出图像,两侧有足够的额外空间,但随机CGRects仍然不相互交叉,它们有时会与中心图像矩形相交。

CGRect aRandomFrame = CGRectMake((aRandomX - 50), (aRandomY - 50), 100, 100);
CGRect imageRect = CGRectMake((self.fixation.center.x - 50), (self.fixation.center.y - 50), 100, 100);

if (CGRectContainsRect(BOUNDARY, aRandomFrame)) {
    BOOL isValidFrame = YES;
    for (NSValue *aFrameValue in [self points]) {
        CGRect aFrame = [aFrameValue CGRectValue];
        if (CGRectIntersectsRect(aFrame, aRandomFrame) || CGRectIntersectsRect(imageRect, aRandomFrame)) {
            isValidFrame = NO;
            break;
        }
    }

    if (isValidFrame) {
        [[self points] addObject:[NSValue valueWithCGRect:aRandomFrame]];
    }
}

作为旁注,BOUNDARY是一个较大的矩形,以确保没有任何随机因素离中心太远。

1 个答案:

答案 0 :(得分:1)

为了说服读者CGRectIntersectsRect无法正常工作,您需要提供一些证明其失败的NSLog证据。

代码看起来还不错,所以怀疑是我们在OP中看不到的东西:

  1. aRandomXaRandomY的计算。我认为看起来像这样:

    CGFloat aRandomX = arc4random_uniform(someView.bounds.size.width);
    CGFloat aRandomY = arc4random_uniform(someView.bounds.size.height);
    
  2. someView 在这里非常重要:它是一个UIView,其中包含所有这些rects的图片视图和坐标系,如果我们在视图中,可能会self.view控制器

    1. BOUNDARY的值,但我敢打赌,这是一个简单的常量矩形,原点为零或小,且大小等于或小于someView

    2. 可能最险恶的罪魁祸首是imageRect的坐标系。如果矩形和边界位于 someView 的坐标系中,那么必须是self.fixation的中心属性。换句话说,self.fixation必须是someView的直接子视图。

    3. 无论它如何与视图层次结构中的someView相关,您都可以通过使用稍微复杂的方法来确保imageRect是正确的:

      CGRect imageRect = [self.fixation convertRect:self.fixation.bounds toView:someView];
      // remember someView might be self.view in a view controller
      // what to do here depends on how your view hierarchy relates to the rects
      

      作为旁注,你的循环有点浪费,因为它每次检查计算的rect时都会检查imageRect与已保存的。你可以这样解决:

      if (CGRectContainsRect(BOUNDARY, aRandomFrame)) {
          if (!CGRectIntersectsRect(imageRect, aRandomFrame)) {
              BOOL isDisjoint = YES;
              for (NSValue *frameValue in self.points) {
                  CGRect aFrame = [frameValue CGRectValue];
                  if (CGRectIntersectsRect(aFrame, aRandomFrame)) {
                      isDisjoint = NO;
                      break;
                  }
              }
              if (isDisjoint) {
                  [self.points addObject:[NSValue valueWithCGRect:aRandomFrame]];
              }
          }
      }
      

      这样做的另一个好处是调试:在第二个条件内部进行分解并检查aRandomFrame是否与imageRect相交。如果是,NSLog矩形并在此处发布。你会发现一个巨大的发现,CGRectContainsRect有一个错误,但它没有,我确定

      相反,如果您看到矩形在该点不相交,并且如果有任何错误,则它将与imageRect一起使用。祝你好运!

相关问题