MKPolyline检测自相交线条 OBJECTIVE C

9
我该如何检测MKPolyline是否与自身相交?我尝试了一些研究,但只找到了涉及两条或更多线路的问题。如果只有一条线/一笔画,我该如何检测它?我想在用户释放触摸后进行检测。
我目前在touchEnded函数中拥有以下代码。
            CGPoint location = [touch locationInView:self.mapView];
            CLLocationCoordinate2D coordinate = [self.mapView convertPoint:location toCoordinateFromView:self.mapView];
            [self.coordinates addObject:[NSValue valueWithMKCoordinate:coordinate]];
            NSInteger numberOfPoints = [self.coordinates count];

            if(numberOfPoints > 2)
            {
                [self setLineLength:[self getLengthArea]];
                if([self lineLength] < 401)
                {
                    if (numberOfPoints > 2)
                    {
                        CLLocationCoordinate2D points[numberOfPoints];
                        for (NSInteger i = 0; i < numberOfPoints; i++) {
                            points[i] = [self.coordinates[i] MKCoordinateValue];
                        }
                        [self.mapView addOverlay:[MKPolyline polylineWithCoordinates:points count:numberOfPoints]];
                    }

                    PCAnnotation *ann = [[PCAnnotation alloc] init];
                    [ann setCoordinate:coordinate];
                    ann.title = @"End";
                    [self.mapView addAnnotation:ann];
                }
                else
                {
                    NSArray *overlayItems = [self.mapView overlays];
                    NSArray *annotations = [self.mapView annotations];
                    [self.mapView removeOverlays:overlayItems];
                    [self.mapView removeAnnotations:annotations];
                }

            }
1个回答

5

MKPolyline继承自MKMultiPoint,后者有一个- (MKMapPoint *)points;方法。

您可以尝试检查所有线段之间的交点。

“这些点按照提供它们的顺序依次相连。”

因此,您可以在每两个点之间创建自己的线段,然后在具有线段数组后检查它们的交点。

下面是用于检查交点的C++代码片段:它可以轻松地转换为Objective-C或其他语言。

public static bool LineSegmentsCross(Vector2 a, Vector2 b, Vector2 c,     Vector2 d)
{
     float denominator = ((b.X - a.X) * (d.Y - c.Y)) - ((b.Y - a.Y) * (d.X - c.X));

     if (denominator == 0)
     {
          return false;
     }

     float numerator1 = ((a.Y - c.Y) * (d.X - c.X)) - ((a.X - c.X) * (d.Y - c.Y));

     float numerator2 = ((a.Y - c.Y) * (b.X - a.X)) - ((a.X - c.X) * (b.Y - a.Y));

     if (numerator1 == 0 || numerator2 == 0)
     {
          return false;
     }

     float r = numerator1 / denominator;
     float s = numerator2 / denominator;

     return (r > 0 && r < 1) && (s > 0 && s < 1);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接