我有一个 MKMapView,我在其中跟踪用户的路径(它是一个正在运行的应用程序),但要求是创建一条具有两种颜色的线。一个用于笔划的中心,另一个用于笔划的边界。为此,我实现了 UIViewController 类的 func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer 方法,以返回渲染器。
我使用的是 Swift 4
有什么想法吗?
提前致谢。
最佳答案
好吧,我在写问题的时候就找到了解决方案,所以我会告诉你解决方案。
首先,您必须创建两个扩展 MKPolyline 类的类
fileprivate class ForegroundOverlay: MKPolyline{
}
fileprivate class BackgroundOverlay: MKPolyline{
}
其次,您必须修改位置更新时触发的事件
var positions = [CLLocationCoordinate2D]()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
positions.append(userLocation.coordinate)
print("Nuber of locations \(positions.count)")
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
speedIndicator.text = "Speed: \(userLocation.speed * 3.6). Altitude: \(userLocation.altitude)"
let fPolyLine = BackgroundOverlay(coordinates: positions, count: positions.count)
mapView.addOverlays([fPolyLine], level: MKOverlayLevel.aboveRoads)
let bPolyLine = ForegroundOverlay(coordinates: positions, count: positions.count)
mapView.addOverlays([bPolyLine], level: MKOverlayLevel.aboveRoads)
}
第三,您必须询问折线是一个类还是另一个类。
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
if overlay is ForegroundOverlay {
renderer.strokeColor = UIColor(red: 230/255, green: 230/255, blue: 1, alpha: 0.5)
renderer.lineWidth = 10
} else {
renderer.strokeColor = UIColor(red: 0, green: 0, blue: 1, alpha: 0.5)
renderer.lineWidth = 30
}
return renderer
}
结果将如下所示
关于ios - 如何在 MKMapView 上用不同的笔画/颜色绘制 2 条 MKPolyline?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47878313/