I am trying to subclass MKPolylineRenderer in order to make custom route drawings in mapkit. I tried following Custom map path line
But no matter what I do, my path does not appear on my map. I am new to CG so I may be missing something simple. Am I allowed to go from polyline to cg, or do I need to convert the polyline to CGPoints?
In my mapview I call my subclass
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolyline *route = overlay;
//MKPolylineRenderer *routeRenderer = [[MKPolylineRenderer alloc] initWithPolyline:route];
CustomPathOverlayRenderer *routeRenderer = [[CustomPathOverlayRenderer alloc] initWithPolyline:route];
//routeRenderer.strokeColor = [UIColor blueColor];
//routeRenderer.lineWidth = 4;
return routeRenderer;
}
return nil;
}
Then i have my CustomPathOverlayRenderer.m
- (id)initWithPolyline:(MKPolyline *)polyline
{
if (self = [super initWithPolyline:polyline])
{
//
}
return self;
}
- (void) drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
CGMutablePathRef path = CGPathCreateMutable();
if (path != nil)
{
CGPathRef path2 = CGPathCreateCopy(path);
//[line.color getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
//UIColor *c2 =[UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:0.4];
CGContextAddPath(context, path);
CGContextSetStrokeColorWithColor(context, [UIColor purpleColor].CGColor);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, MKRoadWidthAtZoomScale(zoomScale));
CGContextStrokePath(context);
CGPathRelease(path);
CGContextSetBlendMode(context, kCGBlendModeSourceAtop);
CGContextAddPath(context, path2);
CGContextSetRGBStrokeColor(context, 1.0f, 0, 0, 0.3f);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, MKRoadWidthAtZoomScale(zoomScale)/2.0f);
CGContextStrokePath(context);
CGPathRelease(path2);
}
}
Figured it out, i do in fact need to add the polyline to CGPath
CGMutablePathRef path = CGPathCreateMutable();
BOOL pathIsEmpty = YES;
for (int i=0;i< polyline.pointCount;i++){
CGPoint point = [self pointForMapPoint:polyline.points[i]];
if (pathIsEmpty){
CGPathMoveToPoint(path, nil, point.x, point.y);
pathIsEmpty = NO;
} else {
CGPathAddLineToPoint(path, nil, point.x, point.y);
}
}
self.path = path;