菜鸟教程小白 发表于 2022-12-11 19:58:16

ios - MapKit - 在没有大量 CPU 使用的情况下跟踪 map 上的用户位置


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

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

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

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

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

    return renderer
}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>你不应该这样做:</p>

<pre><code>var coordinates: = [] {
    didSet{
      let polyine = MKPolyline(coordinates: coordinates, count: coordinates.count)
      mapView.removeOverlays(mapView.overlays)
      mapView.add(polyine)
    }
}
</code></pre>

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

<pre><code>var coordinates: = [] {
    didSet{
      guard coordinates.count &gt; 1 else {
            return
      }
      let count = coordinates.count
      let start = coordinates
      let end = coordinates
      let polyine = MKPolyline(coordinates: , count: 2)
      mapView.add(polyine)
    }
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - MapKit - 在没有大量 CPU 使用的情况下跟踪 map 上的用户位置,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/49621426/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/49621426/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - MapKit - 在没有大量 CPU 使用的情况下跟踪 map 上的用户位置