首页 > 解决方案 > 如何将 MKMapView 中绘制的路线保存为核心数据?

问题描述

在此处输入图像描述

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

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

标签: savemkmapviewswiftui

解决方案


您可以使用MKMapSnapshotter. 不幸的是,您必须stroke手动进入您的路径,使用point(for:)将其转换CLLocationCoordinate2D为:CGPointMKMapSnapshotter.Snapshot

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.polyline与结果相关联的内容,并且您将遍历您的模型,可能会在单个 中抚摸这些不同颜色的部分,但希望这能说明这个想法。MKDirectionsUIBezierPathUIBezierPath


推荐阅读