2

我正在开发与地图和折线相关的应用程序。我想为折线的颜色变化设置动画,我必须做些什么来实现这一点。

我昨天整天都在寻找正确的方法,并决定今天提出问题。

像这样的代码可以做,但在 MKPolyline 上做:

//Assume that this view is a line shape.
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(50, 50, 100, 5);
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view];

[UIView animateWithDuration:0.5f animations:^{
    view.backgroundColor = [UIColor greenColor];
}];

到目前为止,我有:

MKPolylineRenderer 的子类

- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context {
    CGFloat baseWidth = self.lineWidth / zoomScale;
    CGContextSetAlpha(context, 0.5);
    CGContextAddPath(context, self.path);
    CGContextSetStrokeColorWithColor(context, self.strokeColor.CGColor);
    CGContextSetLineWidth(context, baseWidth * 4);
    CGContextSetLineCap(context, self.lineCap);
    CGContextStrokePath(context);
    [super drawMapRect:mapRect zoomScale:zoomScale inContext:context];
}

在 viewController.m

添加折线

- (void)addPolylineToMap {
    CustomPolyline *polyline = [CustomPolyline polylineWithCoordinates:coordinates count:[coordinateArray count]];
    polyline.lineID = polylineID;
    [mapView addOverlay:polyline level:MKOverlayLevelAboveRoads];
}

改变折线颜色(感谢 Anna #Ref: MKPolyline / MKPolylineRenderer 改变颜色而不移除它

- (void)changingPolylineColor {
    for (MKPolyline *overlays in [mapView overlays]) {
        if ([overlays isKindOfClass:[CustomPolyline class]]) {
            CustomPolylineRenderer *renderer = (CustomPolylineRenderer *)[mapView rendererForOverlay:overlays];
            renderer.strokeColor = [self getColorFromArrayWithLineID:[(CustomPolyline *)overlays lineID]];
            [renderer invalidatePath];
        }
    }
}

MapViewDelegate renderForOverlay:

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[CustomPolyline class]]) {
        polylineView = [[CustomPolylineRenderer alloc] initWithPolyline:overlay];
        polylineView.strokeColor = [self getColorFromArrayWithLineID:[(CustomPolyline *)overlay lineID]];
        polylineView.alpha = 0.5f;
        polylineView.lineWidth = 4.0f;
        return polylineView;
    }
    return nil;
}

所以我需要的是当我调用[self changingPolylineColor];地图上的折线时,它会随着动画而改变颜色。

先感谢您。

4

0 回答 0