0

我有一个非常有趣的问题,我找不到解决方案。给定空间中的一组牛矩形或盒子,并给定触摸的坐标,我会找到触摸点所属的盒子。起初,我使用了点到矩形中心的欧式距离。

但是,显然,这并不总是有效。假设下图有 2 个框,中心分别为 a 和 c:

----------
|        |
|        |
|   a    |
|        |
|        |
|   x    |
----------
|        |
|   c    |
|        |
----------

触摸点是“x”,属于框“a”。使用我的算法,x 比 a 更接近 c,这是错误的。有什么建议么?

4

4 回答 4

2

CGRectContainsPoint方法为您完成所有工作。例如,假设您使用了轻击手势。

-(void)handleTap:(UITapGestureRecognizer *)gesture {

    CGPoint point = [gesture locationInView:self.view];

    if (CGRectContainsPoint(box.frame, point)) {
       NSLog@("Point is in Box");
    }       
}
于 2013-07-26T15:23:33.233 回答
1

此答案基于您使用视图的假设,而是您正在处理包含不同矩形区域的模型。

您只需遍历框列表,并使用该功能BOOL CGRectContainsPoint(rect, point);

例如(假设您的矩形被装箱在 NSValues 中,存储在 NSArray 中):

NSArray* arrayOfRects = ...;
CGPoint point = CGPointMake(xTouch, yTouch);

CGRect rectResult = CGRectNull;

for (NSValue* rectObj in arrayOfRects) {
    CGRect rect = [rectObj CGRectValue];
    if (CGRectContainsPoint(rect, point)) {
        rectResult = rect;
        break;
    };
}

if (!CGRectEqualToRect(rectResult, CGRectNull)) {
    // Found a matching rect!
}
else {
    // Touch was outside of any recognised rect
}

此解决方案不会处理重叠的矩形。如果你需要这个,你需要保留一组匹配项,如下所示:

NSArray* arrayOfRects = ...;
CGPoint point = CGPointMake(xTouch, yTouch);

NSMutableArray* rectResultArray = [NSMutableArray array];

for (NSValue* rectObj in arrayOfRects) {
    if (CGRectContainsPoint([rectObj CGRectValue], point)) {
        [rectResultArray addObject:rectObj];
    };
}

if (rectResultArray.count > 0) {
    // Found matching rects!
}
else {
    // Touch was outside of any recognised rect
}
于 2013-07-26T15:25:58.460 回答
0

你是对的,你意识到你不能使用到盒子中心的距离。您可以尝试自己设计和编写代码,也可以使用预制函数CGRectContainsPoint()

于 2013-07-26T15:25:01.173 回答
0

你可以使用这个。

//get the location of the touch
touch = [[event allTouches] anyObject];
location = [touch locationInView:view];

//check if touchpoint belongs to a box
if (CGRectContainsPoint(self.boxA.frame, location))
{
     NSLog(@"Touchpoint is in box A");
}
else if (CGRectContainsPoint(self.boxB.frame, location))
{
     NSLog(@"Touchpoint is in box B");
}
else
{
     NSLog(@"Touchpoint is not in box");
}       
于 2013-07-26T15:27:13.263 回答