Search code examples
iphonecore-graphicsdrawrectcgpathstroke

iPhone - Stroking a path does not work


I have these methods into a MKOverlayView subclass, and I do not understand why filling a path works, and why stroking that same path doesn't work...

- (id) init {
    if (!(self = [super init])) return nil;

    self.opaque = NO;  // If not set, just black squares are drawn

    return self;
}

- (void) drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context {

    // CGRect rects[2] =  {[self rectForMapRect:mapRect],  [self rectForMapRect:self.country.boundingMapRect]};
    // CGContextClipToRects(context, rects, 2);

    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
    CGContextSetRGBFillColor(context, 1.0, 0.0, 1.0, 0.9);
    CGContextSetLineWidth(context, 1.0);

    for (MKPolygon* poly in self.polygons) {

        CGPoint origin = [self pointForMapPoint:poly.points[0]];            
        CGContextMoveToPoint(context, origin.x, origin.y);

        for (int i=1; i<poly.pointCount; i++) {
            CGPoint point = [self pointForMapPoint:poly.points[i]];
            CGContextAddLineToPoint(context, point.x, point.y);
        }

        //CGContextFillPath(context);
        CGContextStrokePath(context);
    }
}


-(BOOL)canDrawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale {
    return YES;
}

Solution

  • How zoomed out are you? It's possible that your stroke is working; it just doesn't show up because it's too thin. Try setting your line width to 1.0 / zoomScale (or, more generally, desiredLineWidth * (1.0 / zoomScale)).

    (Disclaimer: I've never actually used MapKit, so you may need to use zoomScale as it is; based on my reading of the documentation, I would try 1.0 / zoomScale first.)