【问题标题】:How can I draw 2 MKPolyline on MKMapView with different strokes/color?如何在 MKMapView 上用不同的笔划/颜色绘制 2 条 MKPolyline?
【发布时间】:2018-06-01 09:03:24
【问题描述】:

我有一个 MKMapView,我在其中跟踪用户的路径(它是一个正在运行的应用程序),但要求是创建一条有两种颜色的线。一个用于笔画的中心,另一个用于笔画的边框。为此,我正在实现 UIViewController 类的方法 func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer,以返回渲染器。

我正在使用 Swift 4

有什么想法吗?

提前致谢。

【问题讨论】:

    标签: ios mapkit mkmapview swift4


    【解决方案1】:

    好的,我在写问题的时候找到了解决方案,所以我会告诉你解决方案。

    首先,您必须创建两个扩展 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
    }
    

    结果将如下所示

    【讨论】:

    • 不错,但如果有人必须更加动态(我的意思是例如显示来自后端的自定义颜色),这不是最好的方法,因为您必须制作每种颜色一个子类。经过数小时的痛苦,我重写了一个更通用的解决方案:stackoverflow.com/a/68830861。干杯!
    猜你喜欢
    • 2013-02-01
    • 2013-01-29
    • 2012-06-10
    • 1970-01-01
    • 2019-10-02
    • 2013-06-18
    • 2017-06-02
    • 1970-01-01
    相关资源
    最近更新 更多