Advertisement
luismachado

Untitled

Feb 20th, 2019
478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.00 KB | None | 0 0
  1. func generateImage(completion: @escaping (UIImage?) -> Void) {
  2.         let mapSnapshotOptions = MKMapSnapshotter.Options()
  3.  
  4.         let span = MKCoordinateSpan(latitudeDelta: 0.008, longitudeDelta: 0.006)
  5.         let region = MKCoordinateRegion(center: coordinates, span: span)
  6.  
  7.         // Set the region of the map that is rendered.
  8.         mapSnapshotOptions.region = region
  9.  
  10.         // Set the scale of the image. We'll just use the scale of the current device, which is 2x scale on Retina screens.
  11.         mapSnapshotOptions.scale = UIScreen.main.scale
  12.  
  13.         // Set the size of the image output.
  14.         mapSnapshotOptions.size = CGSize(width: 300, height: 300)
  15.  
  16.         // Show buildings and Points of Interest on the snapshot
  17.         mapSnapshotOptions.showsBuildings = true
  18.         mapSnapshotOptions.showsPointsOfInterest = true
  19.  
  20.         let snapShotter = MKMapSnapshotter(options: mapSnapshotOptions)
  21.         let rect = CGRect(x: 0, y: 0, width: 300, height: 300)
  22.  
  23.         snapShotter.start { (snapshot, error) in
  24.             guard let snapshot = snapshot, error == nil else {
  25.                 completion(nil)
  26.                 return
  27.             }
  28.  
  29.             UIGraphicsBeginImageContextWithOptions(mapSnapshotOptions.size, true, 0)
  30.             snapshot.image.draw(at: .zero)
  31.  
  32.             let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
  33.             let pinImage = pinView.image
  34.  
  35.             var point = snapshot.point(for: self.coordinates)
  36.  
  37.             if rect.contains(point) {
  38.                 let pinCenterOffset = pinView.centerOffset
  39.                 point.x -= pinView.bounds.size.width / 2
  40.                 point.y -= pinView.bounds.size.height / 2
  41.                 point.x += pinCenterOffset.x
  42.                 point.y += pinCenterOffset.y
  43.                 pinImage?.draw(at: point)
  44.             }
  45.  
  46.             let image = UIGraphicsGetImageFromCurrentImageContext()
  47.  
  48.             UIGraphicsEndImageContext()
  49.  
  50.             completion(image)
  51.         }
  52.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement