15

I can create a line between two points fairly easy with the below code (part of it anyways) How could I make the line dotted instead of solid? Also would it be possible to change the opacity the longer the line is?

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay
{
    MKPolylineRenderer *renderer =[[MKPolylineRenderer alloc] initWithPolyline:overlay];
    renderer.strokeColor = [UIColor orangeColor];
    renderer.lineWidth = 3.0;

    return renderer;
}
jdross
  • 1,188
  • 2
  • 11
  • 30

2 Answers2

51

You can use the lineDashPattern property to create the pattern you want for the line.

MKPolylineRenderer is a subclass of MKOverlayPathRenderer which has that property and a few others (see the link to the documentation).

For example, this sets the pattern to a line 2 points long followed by a 5 point gap. The pattern is repeated for the entire length of the polyline.

renderer.lineDashPattern = @[@2, @5];


For the opacity, you can either apply an alpha to the strokeColor:

renderer.strokeColor = [[UIColor orangeColor] colorWithAlphaComponent:0.5];

or set the alpha property:

renderer.alpha = 0.5;

Not sure what you mean by "the longer the line is" part of the question.

  • Anna, thanks for the help. That makes sense. In regards to the "longer line" I was wondering if its possible to change the alpha value from 1 to .1 within the line itself. for example the starting point would be an alpha value of 1 and the end point maybe .1 – jdross Dec 13 '13 at 18:17
  • Varying the alpha along the line would be a gradient and unfortunately that ability isn't built into the standard renderers. You'll have to create a custom overlay renderer and do the drawing manually. [This](http://stackoverflow.com/a/20159374/467105) and [this](http://stackoverflow.com/a/19377748/467105) can help you get started if you want to pursue that path. –  Dec 13 '13 at 19:20
  • @Anna great answer..but what if i need the first dash to be small and second dash to be longer and line repeating this pattern ? – LC 웃 Jun 12 '15 at 06:25
  • i found it polylineRenderer.lineDashPattern = [5,10,2,10] – LC 웃 Jun 12 '15 at 06:28
8

Answer in Swift

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    guard let polyline = overlay as? MKPolyline else {
        fatalError("Not a MKPolyline")
    }

    let renderer = MKPolylineRenderer(polyline: polyline)

    renderer.strokeColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
    renderer.lineWidth = 8
    renderer.lineDashPattern = [0, 10]

    return renderer
} 

enter image description here

Abin Baby
  • 586
  • 6
  • 17
  • 2
    Honestly ... should this be an answer? This is just a single line and I don't think anybody will ask to convert it in swift. – TheTiger Apr 05 '18 at 11:13