ios – MKPolyline / MKPolylineRenderer改变颜色而不删除它

我正在使用地图应用程序,我想问如何更改折线颜色而不删除并再次添加它,我在stackoverflow中找到了这个主题 https://stackoverflow.com/questions/24226290/mkpolylinerenderer-change-color-without-removing-overlay,但这不涉及我的问题,我没有触及线,所以不需要处理 – [MKMapViewDelegate mapView:didSelectAnnotationView:]

这样做有可能吗?

编辑:我想要做的是平滑地改变折线颜色(通过着色颜色 – 像动画一样的声音)如果您对如何设置此折线的动画有任何想法,请同时告诉我.谢谢

解决方法

复杂的动画或着色/渐变可能需要创建自定义叠加渲染器类.

这些其他答案给出了关于如何绘制渐变折线的想法,动画也最需要自定义叠加渲染器:

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

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

但是,如果您只想更新线条的颜色(例如从蓝色到红色),那么您可以按照以下方式执行此操作:

>获取您想要更改的MKPolyline的参考.
>获取对步骤1中获得的折线的MKPolylineRenderer的引用.这可以通过调用地图视图的rendererForOverlay:instance方法(与mapView:rendererForOverlay:delegate方法不同)来完成.
>更新渲染器的strokeColor.
>在渲染器上调用invalidatePath.

不确定你想要什么,但你可以通过改变颜色并在定时步骤中逐渐调用invalidatePath来“动画”从蓝色到红色的颜色.

另一个重要的事情是确保rendererForOverlay委托方法也使用行的“当前”颜色,以防地图视图在您直接更改渲染器的strokeColor后调用委托方法.

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

您可以将线的当前颜色保留在类级变量中,并在委托方法和要更改线的颜色的位置使用它.

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

例:

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

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...