如何在MKMapSnapshotter上绘制CLLocationCoordinate2Ds(在mapView打印的图像上绘制)

时间:2019-02-13 19:50:16

标签: ios swift mapkit mkmapsnapshotter

我有带CLLocationCoordinate2D数组的mapView。我使用这些位置通过MKPolyline在mapView上画线。现在我想将其存储为UIimage。我发现那里有类MKMapSnapshotter,但不幸的是我无法在其上绘制叠加层“ Snapshotter对象无法捕获您的应用程序创建的任何叠加层或注释的视觉表示。”所以我只得到空白的地图图像。有什么方法可以让我的覆盖物获得图像吗?

private func generateImageFromMap() {
    let mapSnapshotterOptions = MKMapSnapshotter.Options()
    guard let region = mapRegion() else { return }
    mapSnapshotterOptions.region = region
    mapSnapshotterOptions.size = CGSize(width: 200, height: 200)
    mapSnapshotterOptions.showsBuildings = false
    mapSnapshotterOptions.showsPointsOfInterest = false


    let snapShotter = MKMapSnapshotter(options: mapSnapshotterOptions)
    snapShotter.start() { snapshot, error in
        guard let snapshot = snapshot else {
//do something with image .... 
            let mapImage = snapshot...
        }
    }
}

如何在该图像上放置覆盖物?也许还有其他方法可以解决这个问题。

1 个答案:

答案 0 :(得分:1)

不幸的是,您必须自己绘制它们。幸运的是,Range("A2:A10000")具有便捷的point(for:)方法,可以将快照中的MKSnapshot转换为CLLocationCoordinate2D

例如,假设您有一个CGPoint数组:

CLLocationCoordinate2D

然后显示以下地图视图(坐标与private var coordinates: [CLLocationCoordinate2D]? private func generateImageFromMap() { guard let region = mapRegion() else { return } let options = MKMapSnapshotter.Options() options.region = region options.size = CGSize(width: 200, height: 200) options.showsBuildings = false options.showsPointsOfInterest = false MKMapSnapshotter(options: options).start() { snapshot, error in guard let snapshot = snapshot else { return } let mapImage = snapshot.image let finalImage = UIGraphicsImageRenderer(size: mapImage.size).image { _ in // draw the map image mapImage.draw(at: .zero) // only bother with the following if we have a path with two or more coordinates guard let coordinates = self.coordinates, coordinates.count > 1 else { return } // convert the `[CLLocationCoordinate2D]` into a `[CGPoint]` let points = coordinates.map { coordinate in snapshot.point(for: coordinate) } // build a bezier path using that `[CGPoint]` let path = UIBezierPath() path.move(to: points[0]) for point in points.dropFirst() { path.addLine(to: point) } // stroke it path.lineWidth = 1 UIColor.blue.setStroke() path.stroke() } // do something with finalImage } } 一样,由MKPolyline渲染,像往常一样):

enter image description here

上面的代码将创建此mapView(_:rendererFor:)

enter image description here