对于导航应用程序,我需要检测用户何时偏离给定的行车路径(表示为坐标列表),所以我想要做的是每当我为用户获得新的位置更新时,检查不好如果此位置在路径中。 太复杂了吗?
答案 0 :(得分: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);
}