MKPolyline / MKPolylineRenderer 更改颜色而不删除它

MKPolyline / MKPolylineRenderer changing color without remove it

我在使用地图应用程序,我想问一下如何在不删除的情况下更改折线颜色并再次添加,我在 Whosebug 中找到了这个主题 但这不涉及我的问题,我没有碰线,所以不需要做 -[MKMapViewDelegate mapView:didSelectAnnotationView:]

那有可能吗?

编辑:我想做的是平滑地改变折线颜色(通过对颜色进行阴影处理 - 听起来像动画)如果您对如何为这条折线设置动画有任何想法,也请告诉我。谢谢

复杂的动画或 shading/gradients 可能需要创建自定义叠加渲染器 class。

这些其他答案提供了有关如何绘制渐变折线和动画的想法,它们很可能也需要自定义叠加渲染器:

  • how to customize MKPolyLineView to draw different style lines
  • Gradient Polyline with MapKit ios
  • Draw CAGradient within MKPolyLineView

Apple's Breadcrumb sample app 还有一个自定义渲染器的示例,您可能会发现它很有用。


但是,如果您只想更新线条的颜色(比如从蓝色到红色),那么您可以按如下方式进行:

  1. 获取对您要更改的 MKPolyline 的引用。
  2. 获取对步骤1中获得的折线的MKPolylineRenderer的引用。这可以通过调用地图视图的rendererForOverlay:实例方法来完成(与mapView:rendererForOverlay:不同委托方法。
  3. 更新渲染器的strokeColor
  4. 在渲染器上调用 invalidatePath

不确定您想要什么,但您可以 "animate" 通过更改颜色并按定时步骤逐渐调用 invalidatePath 来使颜色从蓝色变为红色。

另一个重要的事情是确保 rendererForOverlay delegate 方法也使用线条的 "current" 颜色,以防地图视图在之后调用委托方法您直接更改了渲染器的 strokeColor

否则,在平移或缩放地图后,折线的颜色将变回委托方法中设置的任何颜色。

您可以将线条的当前颜色保存在 class 级变量中,并在委托方法和要更改线条颜色的地方使用它。

class 级变量的替代方法(可能更好)是使用 MKPolyline 的 title 属性 来保持其颜色或自定义折线覆盖 class(不是渲染器),颜色为 属性.

示例:

@property (nonatomic, strong) UIColor *lineColor;
//If you need to keep track of multiple overlays, 
//try using a NSMutableDictionary where the keys are the 
//overlay titles and the value is the UIColor.

-(void)methodWhereYouOriginallyCreateAndAddTheOverlay
{
    self.lineColor = [UIColor blueColor];  //line starts as blue
    MKPolyline *pl = [MKPolyline polylineWithCoordinates:coordinates count:count];
    pl.title = @"test";
    [mapView addOverlay:pl];
}

-(void)methodWhereYouWantToChangeLineColor
{
    self.lineColor = theNewColor;

    //Get reference to MKPolyline (example assumes you have ONE overlay)...
    MKPolyline *pl = [mapView.overlays objectAtIndex:0];

    //Get reference to polyline's renderer...
    MKPolylineRenderer *pr = (MKPolylineRenderer *)[mapView rendererForOverlay:pl];
    pr.strokeColor = self.lineColor;
    [pr invalidatePath];
}

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineRenderer *pr = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        pr.strokeColor = self.lineColor;
        pr.lineWidth = 5;
        return pr;
    }

    return nil;
}

你应该看看 MKOverlayPathRenderer 方法 - invalidatePath.

文档中说:

Call this method when a change in the path information would require you to recreate the overlay’s path. This method sets the path property to nil and tells the overlay renderer to redisplay its contents.

所以,此时,您应该可以更改绘图颜色了。