OGeek|极客世界-中国程序员成长平台

标题: ios - MapKit - 在没有大量 CPU 使用的情况下跟踪 map 上的用户位置 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:58
标题: ios - MapKit - 在没有大量 CPU 使用的情况下跟踪 map 上的用户位置

当用户在 MKMapView 上移动时,我正在尝试用一条线来跟踪用户的位置。问题是我目前正在尝试使用折线跟踪用户的位置,但是当用户的位置更新时,由于添加了一个新点,我不得不重新绘制该线。这占用了大量的 cpu 资源,因为我经历的最大 cpu 使用率约为 200%。我应该如何在不使用大部分可用 cpu 资源的情况下在用户后面绘制路径?以下是我的代码:

var coordinates: [CLLocationCoordinate2D] = [] {
    didSet{
            let polyine = MKPolyline(coordinates: coordinates, count: coordinates.count)
            mapView.removeOverlays(mapView.overlays)
            mapView.add(polyine)
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    coordinates.append(locations[0].coordinate)
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(overlay: overlay)

    renderer.strokeColor = UIColor.blue
    renderer.lineWidth = 5.0

    return renderer
}



Best Answer-推荐答案


你不应该这样做:

var coordinates: [CLLocationCoordinate2D] = [] {
    didSet{
        let polyine = MKPolyline(coordinates: coordinates, count: coordinates.count)
        mapView.removeOverlays(mapView.overlays)
        mapView.add(polyine)
    }
}

因为它们对 CPU 造成了很大的压力。比如下面的代码怎么样:

var coordinates: [CLLocationCoordinate2D] = [] {
    didSet{
        guard coordinates.count > 1 else {
            return
        }
        let count = coordinates.count
        let start = coordinates[count-1]
        let end = coordinates[count-2]
        let polyine = MKPolyline(coordinates: [start, end], count: 2)
        mapView.add(polyine)
    }
}

关于ios - MapKit - 在没有大量 CPU 使用的情况下跟踪 map 上的用户位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49621426/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4