MKPolyline奇怪的渲染与缩放MapKit有关

时间:2016-10-25 11:08:54

标签: ios swift mapkit mkoverlay mkpolyline

我有非常简单的View Controller来演示MKPolyline的这种奇怪的渲染行为。没有什么特别的,只是正常的api电话。

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var map: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        map.delegate = self
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let p1 = CLLocationCoordinate2D(latitude: 51, longitude: 13)
        var coords = [
            p1,
            CLLocationCoordinate2D(latitude: 51.1, longitude: 13),
            CLLocationCoordinate2D(latitude: 51.2, longitude: 13),
            CLLocationCoordinate2D(latitude: 51.3, longitude: 13)
        ]

        let polyline = MKPolyline(coordinates: &coords, count: coords.count)
        map.addOverlays([polyline], level: .aboveRoads)
        let cam = MKMapCamera(lookingAtCenter: p1, fromDistance: 1000, pitch: 45, heading: 0)
        map.setCamera(cam, animated: true)
    }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let r = MKPolylineRenderer(overlay: overlay)
        r.strokeColor = UIColor.blue
        return r
    }
}

折线的渲染非常奇怪。在缩放和平移期间您可以看到一些工件。

看看下面的图片:

初始屏幕 Initial Screen

经过一番淘汰 After some panning

缩小并再次放大后 After zooming out and zooming in again

如何解决这个问题?我试图实现我自己的渲染器,但它的情况相同。像过度缓存一样,并没有按时重绘。我从iOS SDK 10 xCode 8开始使用iOS 10,iPhone 6,模拟器。

1 个答案:

答案 0 :(得分:6)

Swift 3解决方案:

创建MKPolylineRenderer的子类

class CustomPolyline: MKPolylineRenderer {

    override func applyStrokeProperties(to context: CGContext, atZoomScale zoomScale: MKZoomScale) {
        super.applyStrokeProperties(to: context, atZoomScale: zoomScale)
        UIGraphicsPushContext(context)
        if let ctx = UIGraphicsGetCurrentContext() {
            ctx.setLineWidth(self.lineWidth)
        }
    }
}

然后在rendererFor MapKit委托中使用它:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = CustomPolyline(overlay: overlay)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 100
        return renderer
}

缩放后,折线不会重新渲染,从而避免了瑕疵