0

对于导航应用程序,我需要检测用户何时偏离给定的驾驶路径(表示为坐标列表),所以我想要做的是每当我为用户获取新的位置更新时,我会检查这个位置是否在路径中。是不是太复杂了?

4

1 回答 1

1

对于类似的问题,我使用 CGPath 创建了一个路径,然后测试一个点是否在路径中。通过控制路径宽度,您可以很容易地控制偏差量。

这是示例代码,用于测试触摸事件中的锥体:

- (void)createPath {
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(   path, nil, 400, 300);
    CGPathAddLineToPoint(path, nil, 500, 300);
    CGPathAddLineToPoint(path, nil, 500, 400);
    CGPathAddLineToPoint(path, nil, 400, 400);
    self.pathRef   = path;

    CGContextRef context = [self createOffscreenContext];
    CGContextSetLineWidth(context, self.pathWidth);

    CGContextBeginPath(context);
    CGContextAddPath(context, self.pathRef);    
}

- (CGContextRef)createOffscreenContext {
    CFMutableDataRef empty = CFDataCreateMutable(NULL, 0);
    CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData(empty);
    self.offscreenContext = CGPDFContextCreate(consumer, NULL, NULL);
    CGDataConsumerRelease(consumer);
    CFRelease(empty);

    return self.offscreenContext;
}

// Optional, not needed for the test to work
-(void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetStrokeColorWithColor(context, self.colorRef);
    CGContextSetLineWidth(context, self.pathWidth);

    CGContextAddPath(context, self.pathRef);
    CGContextStrokePath(context);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];

    BOOL isPointInPath = CGContextPathContainsPoint(self.offscreenContext, touchPoint, kCGPathStroke);

    NSLog(@"pip: %d, x: %3.0f, y: %3.0f", isPointInPath, touchPoint.x, touchPoint.y);
}
于 2011-11-26T02:49:25.740 回答