如何将 MKMapView 中绘制的路线保存为核心数据?

How to save route drawn in MKMapView as Core data?

我在 MKMapView 上画了一条路线。 我保存了位置数据以绘制路线。 每天存储的位置数据为数十兆字节。 所以我试图减少存储的数据,我只需要一张带有过去路线的地图。

除了数百个存储的位置数据之外,还有什么简单的数据可以使路线如屏幕截图所示?

您可以使用 MKMapSnapshotter. Unfortunately, you’ll have to stroke your path manually, using point(for:)CLLocationCoordinate2D 转换为 MKMapSnapshotter.Snapshot 中的 CGPoint:

let options = MKMapSnapshotter.Options()
options.region = mapView.region
options.size = mapView.bounds.size

MKMapSnapshotter(options: options).start { snapshot, _ in
    guard let snapshot = snapshot else { return }

    let image = UIGraphicsImageRenderer(size: options.size).image { _ in
        snapshot.image.draw(at: .zero)

        let count = route.polyline.pointCount
        let points = route.polyline.points()
        guard count > 1 else { return }

        let path = UIBezierPath()
        path.move(to: snapshot.point(for: points[0].coordinate))
        for i in 1 ..< count {
            path.addLine(to: snapshot.point(for: points[i].coordinate))
        }

        path.lineWidth = 4
        path.lineCapStyle = .round
        path.lineJoinStyle = .round
        UIColor.blue.withAlphaComponent(0.75).setStroke()

        path.stroke()
    }

    guard let data = image.pngData() else { return }

    // you can now write this `data` to persistent storage
}

产生:

现在,上面显然只是将 route.polylineMKDirections 相关联的结果设为单个 UIBezierPath,并且您可能会迭代模型单独抚摸每个不同颜色的部分 UIBezierPath,但希望这能说明这个想法。