7

任何人都可以帮助我MKPolyline使用附加参数颜色进行自定义吗?

CustomPolyline.swift

import Foundation
import MapKit
class CustomPolyline : MKPolyline {
    let coordinates: UnsafeMutablePointer<CLLocationCoordinate2D>
    let count : Int = 0
    let color : String = "ff0000"
    init(coordinates: UnsafeMutablePointer<CLLocationCoordinate2D>, count: Int, color: String) {

        self.coordinates = coordinates
        self.count = count
        self.color = color
    }
}

在里面

Polyline = CustomPolyline(coordinates: &Path, count: Path.count, color: "ff0000")
self.mapView.addOverlay(Polyline)

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {      
        if (overlay is CustomPolyline) {
            var pr = MKPolylineRenderer(overlay: overlay);
            pr.strokeColor = UIColor.colorWithRGBHex(0xff0000).colorWithAlphaComponent(0.5);
            pr.lineWidth = 10;
            return pr;
        }

        return nil
    }

我的解决方案不起作用,我不知道为什么。折线根本不可见。我是 SWIFT 的初学者,所以我认为问题出在我的CustomPolyline课堂上。感谢帮助。

4

3 回答 3

13

它可以比我通过的简单得多:

班级

import Foundation
import MapKit

class CustomPolyline : MKPolyline {

    var color: String?
}

在里面

cPolyline = CustomPolyline(coordinates: &Path, count: Path.count)
cPolyline.color = "#ff0000"
self.mapView.addOverlay(cPolyline)

func mapView(mapView: MKMapView!, rendererForOverlay overlay: CustomPolyline!) -> MKOverlayRenderer! {      

            var pr = MKPolylineRenderer(overlay: overlay);
            pr.strokeColor = UIColor(rgba: overlay.color);
            pr.lineWidth = 10;
            return pr;

    }
于 2014-09-24T09:56:39.763 回答
4

正如 user3470987 指出的那样,修改默认的“rendererForOverlay”委托函数可能存在问题。如果您想添加 MKPolyline 以外的其他类型的叠加层,这也可能会很困难。

班级

import Foundation
import MapKit

class Polyline: MKPolyline {
    var color: UIColor?
}

渲染功能

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {

    if let polyline = overlay as? Polyline {

        let polylineRenderer = MKPolylineRenderer(overlay: polyline)
        polylineRenderer.strokeColor = polyline.color
        polylineRenderer.lineWidth = 3
        return polylineRenderer
    }

    return MKOverlayRenderer(overlay: overlay)

}
于 2017-05-31T20:49:04.077 回答
1

另一个最简单的解决方案:

extension UIColor {
    static var rendererColor: UIColor {
        return UIColor(red: 65/255, green: 65/255, blue: 65/255, alpha: 1)
    }
}

以及用途:

renderer.strokeColor = UIColor.renderer
于 2018-07-10T21:48:40.937 回答