2016-11-22 69 views
9

如何檢測MKPolyline是否相交?我試圖研究這個,但只發現有兩行或更多行的問題。如何檢測我是否只有一行/一行?我想在用戶釋放觸摸後檢測它。MKPolyline檢測自相交線目標C

我現在的觸摸功能有這段代碼。

  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]; 
       } 

      } 

回答

4

MKPolyline繼承形式MKMultiPoint 具有- (MKMapPoint *)points;方法,

你可以嘗試檢查所有線段之間的交叉點。

「這些點是按照它們提供的順序端到端連接的。」

因此,您可以在每個2點, 之間創建自己的線段,並在您有一個線段數組後,您可以檢查其交點。

這是一個用於檢查交叉點的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); 
}