2

有一种方法,当用户在视图外触摸时,应用程序会检测到该视图内更近的点?我想像下图一样检测。

例子

编辑:

CGPoint touchPoint = [[touches anyObject] locationInView:self.view];

if (CGRectContainsPoint([_grayView frame], touchPoint)) {
    // The touch was inside the gray view
} else {
    // The touch was outside the view. Detects where's the closer CGPoint inside the gray view.
    // The detection must be related to the whole view (In the image example, the CGPoint returned would be related to the whole screen)
}
4

3 回答 3

0

你只需要一点数学:

  1. locationInView:以所讨论的观点作为论据,要求触摸它。
  2. 比较该点x与视图的bounds,钳制到该 的极值CGRect
  3. 没有第三步,上面的结果就是你要找的点。
于 2012-11-03T16:02:08.133 回答
0
static float bound(float pt, float min, float max)
{
    if(pt < min) return min;
    if(pt > max) return max;
    return pt;
}

static CGPoint boundPoint(CGPoint touch, CGRect bounds)
{
    touch.x = bound(touch.x, bounds.origin.x, bounds.origin.x + bounds.size.width;
    touch.y = bound(touch.y, bounds.origin.y, bounds.origin.y + bounds.size.height;
    return touch;
}
于 2012-11-03T16:15:09.263 回答
0

试试这个代码!

CGPoint pt = [touches locationInView:childView];
if(pt.x >= 0 && pt.x <= childView.frame.size.width 
&& pt.y >= 0 && pt.y <= childView.frame.size.height) {
   NSLog(@"Touch inside rect");
   return;
}
pt.x = MIN(childView.frame.size.width, MAX(0, pt.x));
pt.y = MIN(childView.frame.size.height, MAX(0, pt.y));
// and here is the point
NSLog(@"The closest point is %f, %f", pt.x, pt.y);
于 2012-11-03T16:19:12.107 回答