How to draw UIBezierPath overlay on MKMapView?

为君一笑 提交于 2020-01-02 21:54:31

问题


I try to subclass from MKOverlayPathRenderer and implement -createPath

- (void)createPath
{
    MKPolyline *line = (id)self.overlay;

    MKMapPoint *points = line.points;
    NSUInteger pointCount = line.pointCount;

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, points[0].x, points[0].y);

    for (int i = 1; i < pointCount; i++) {
        CGPathAddLineToPoint(path, NULL, points[i].x, points[i].y);
    }
    [self setPath:path];
}

I create overlay here:

CLLocationCoordinate2D coordinates[events.count];
for (int i; i < events.count; i++) {
    coordinates[i] = [events[i] coordinate];
}

MKPolyline *line = [MKPolyline polylineWithCoordinates:coordinates count:events.count];
[mapView addOverlay:line];

And then create renderer here:

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(MKPolyline *)overlay
{
    MKBezierPathRenderer *r = [[MKBezierPathRenderer alloc] initWithOverlay:overlay];
    r.lineWidth = 8.f;
    r.strokeColor = [UIColor redColor];
    r.fillColor = [UIColor redColor];

    return r;
}

But I can't see any lines on map. What should I do? Thanx.

P.S. CGPathAddLineToPoint is for tests now, in production I need curves.


回答1:


According to Anna's answer you should use [self pointForMapPoint:points[i]] instead of points[i]

- (void)createPath
{
    MKPolyline *line = (id)self.overlay;

    MKMapPoint *points = line.points;
    NSUInteger pointCount = line.pointCount;

    CGMutablePathRef path = CGPathCreateMutable();
    CGPoint point = [self pointForMapPoint:points[0]];
    CGPathMoveToPoint(path, NULL, point.x, point.y);

    for (int i = 1; i < pointCount; i++) {
        point = [self pointForMapPoint:points[i]];
        CGPathAddLineToPoint(path, NULL, point.x, point.y);
    }
    [self setPath:path];
}


来源:https://stackoverflow.com/questions/28394074/how-to-draw-uibezierpath-overlay-on-mkmapview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!