防止 MKPolygon 打结

Prevent MKPolygon to have knots

我正在开发一个带有地图的应用程序,用户可以在其中绘制多边形区域。

我的问题是可以用节点绘制多边形(见图)(我不知道 节点 是否正确)。我没有找到防止多边形打结的简单方法。 对于附图的情况,我希望去除小卷曲甚至平滑轮廓

你知道怎么做吗?

在用户触摸屏幕时绘制多边形的过程确实使用了 MKPolylineMKPolygonMKOverlay,如下所示:

- (void)touchesBegan:(UITouch*)touch
{
    CGPoint location = [touch locationInView:self.mapView];
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:location toCoordinateFromView:self.mapView];
    [self.coordinates addObject:[NSValue valueWithMKCoordinate:coordinate]];
}

- (void)touchesMoved:(UITouch*)touch
{
    CGPoint location = [touch locationInView:self.mapView];
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:location toCoordinateFromView:self.mapView];
    [self.coordinates addObject:[NSValue valueWithMKCoordinate:coordinate]];
}

- (void)touchesEnded:(UITouch*)touch
{
    CGPoint location = [touch locationInView:self.mapView];
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:location toCoordinateFromView:self.mapView];
    [self.coordinates addObject:[NSValue valueWithMKCoordinate:coordinate]];
    [self didTouchUpInsideDrawButton:nil];
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKOverlayPathView *overlayPathView;

    if ([overlay isKindOfClass:[MKPolygon class]])
    {
        // create a polygonView using polygon_overlay object
        overlayPathView = [[MKPolygonView alloc] initWithPolygon:overlay];
        overlayPathView.fillColor   = [UIColor redColor];
        overlayPathView.lineWidth = 1.5;
        return overlayPathView;
    }
    else if ([overlay isKindOfClass:[MKPolyline class]])
    {
        overlayPathView = [[MKPolylineView alloc] initWithPolyline:(MKPolyline *)overlay];
        overlayPathView.fillColor   = [UIColor redColor];
        overlayPathView.lineWidth = 3;
        return overlayPathView;
    }
    return nil;
}
  1. MKOverlayPathView 是 deprecated since iOS 7.0. You'd use MKOverlayRenderer 而不是它以及相关的地图委托方法。
  2. 尝试使用 miterLimit 属性 的 MKOverlayRenderer。

示例:

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[MKPolygon class]]) {
        MKPolygonRenderer *polygonRenederer = [[MKPolygonRenderer alloc] initWithPolygon:overlay];
        polygonRenederer.fillColor = [UIColor redColor];
        polygonRenederer.lineWidth = 1.5;
        polygonRenederer.miterLimit = 10;
        return polygonRenederer;
    } else if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineRenderer *lineRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        lineRenderer.strokeColor = [UIColor redColor];
        lineRenderer.lineWidth = 3;
        return lineRenderer;
    }
    return nil;
}