How do you add MKPolylines to MKSnapShotter in swift 3?
Asked Answered
C

3

10

Is there a way to take a screenshot of mapView and include the polyline? I believe I need to draw CGPoint's on the image that the MKSnapShotter returns, but I am unsure on how to do so.

Current code

      func takeSnapshot(mapView: MKMapView, withCallback: (UIImage?, NSError?) -> ()) {
    let options = MKMapSnapshotOptions()
    options.region = mapView.region
    options.size = mapView.frame.size
    options.scale = UIScreen.main().scale

    let snapshotter = MKMapSnapshotter(options: options)


    snapshotter.start() { snapshot, error in
        guard snapshot != nil else {
            withCallback(nil, error)
            return
        }

        if let image = snapshot?.image{



            withCallback(image, nil)

            for coordinate in self.area {

                image.draw(at:snapshot!.point(for: coordinate))

            }

        }

    }
}
Ciapha answered 18/7, 2016 at 22:18 Comment(4)
In Putting Map Kit in Perspective video, Apple demonstrates that if you want to include annotations in a snapshot, you have to manually draw them yourself. (Bewildering, yes, but it is what it is.) I assume the same is true for overlays such as the MKPolyline.Zoology
Thank you, I will check it out.Ciapha
Okay, so the video was informative, but didn't really help.Ciapha
I would have thought that the demo, manually rendering the annotation pins in a snapshot, would have given you enough clues how to do the equivalent with overlays...Zoology
M
21

I had the same problem today. After several hours of research, here is how I solve it.

The following codes are in Swift 3.

1. Init your polyline coordinates array

// initial this array with your polyline coordinates
var yourCoordinates = [CLLocationCoordinate2D]() 
yourCoorinates.append( coordinate 1 )
yourCoorinates.append( coordinate 2 )
...
// you can use any data structure you like

2. take the snapshot as usual, but set the region based on your coordinates:

func takeSnapShot() {
    let mapSnapshotOptions = MKMapSnapshotOptions()

    // Set the region of the map that is rendered. (by polyline)
    let polyLine = MKPolyline(coordinates: &yourCoordinates, count: yourCoordinates.count)
    let region = MKCoordinateRegionForMapRect(polyLine.boundingMapRect)

    mapSnapshotOptions.region = region

    // Set the scale of the image. We'll just use the scale of the current device, which is 2x scale on Retina screens.
    mapSnapshotOptions.scale = UIScreen.main.scale

    // Set the size of the image output.
    mapSnapshotOptions.size = CGSize(width: IMAGE_VIEW_WIDTH, height: IMAGE_VIEW_HEIGHT)

    // Show buildings and Points of Interest on the snapshot
    mapSnapshotOptions.showsBuildings = true
    mapSnapshotOptions.showsPointsOfInterest = true

    let snapShotter = MKMapSnapshotter(options: mapSnapshotOptions)

    snapShotter.start() { snapshot, error in
        guard let snapshot = snapshot else {
            return
        }
        // Don't just pass snapshot.image, pass snapshot itself!
        self.imageView.image = self.drawLineOnImage(snapshot: snapshot)
    }
}

3. Use snapshot.point() to draw Polylines on Snapshot Image

func drawLineOnImage(snapshot: MKMapSnapshot) -> UIImage {
    let image = snapshot.image

    // for Retina screen
    UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, true, 0)

    // draw original image into the context
    image.draw(at: CGPoint.zero)

    // get the context for CoreGraphics
    let context = UIGraphicsGetCurrentContext()

    // set stroking width and color of the context
    context!.setLineWidth(2.0)
    context!.setStrokeColor(UIColor.orange.cgColor)

    // Here is the trick :
    // We use addLine() and move() to draw the line, this should be easy to understand.
    // The diificult part is that they both take CGPoint as parameters, and it would be way too complex for us to calculate by ourselves
    // Thus we use snapshot.point() to save the pain.
    context!.move(to: snapshot.point(for: yourCoordinates[0]))
    for i in 0...yourCoordinates.count-1 {
      context!.addLine(to: snapshot.point(for: yourCoordinates[i]))
      context!.move(to: snapshot.point(for: yourCoordinates[i]))
    }

    // apply the stroke to the context
    context!.strokePath()

    // get the image from the graphics context
    let resultImage = UIGraphicsGetImageFromCurrentImageContext()

    // end the graphics context 
    UIGraphicsEndImageContext()

    return resultImage!
}

That's it, hope this helps someone.

References

Masera answered 8/2, 2017 at 7:30 Comment(3)
@user287589 How to calculate region span to have insets on snapshot?Redundant
@AymenHARRATH I don't know. SorryMasera
I tried running this snippet of code. It gives me following error in this line: context!.setLineWidth(2.0) Error message says: "Fatal error: Unexpectedly found nil while unwrapping an Optional value"Cymatium
L
1

What is wrong with:

snapshotter.start( completionHandler: { snapshot, error in
  guard snapshot != nil else {
    withCallback(nil, error)
    return
  }

  if let image = snapshot?.image {
    withCallback(image, nil)

    for coordinate in self.area {
      image.draw(at:snapshot!.point(for: coordinate))
    }

  }
})
Lutenist answered 4/11, 2016 at 4:28 Comment(1)
I ended up just storing the coordinates in an array, then displaying them on a Map I created in another view.Ciapha
P
0

If you just want a copy of the image the user sees in the MKMapView, remember that it's a UIView subclass, and so you could do this...

public extension UIView {
    public var snapshot: UIImage? {
        get {
            UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)
            self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }
}

// ...
if let img = self.mapView.snapshot {
    // Do something
}
Padegs answered 12/9, 2018 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.