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

Mar*_*sta 11 mapkit ios mkoverlay mkpolyline swift

我有非常简单的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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

看看下面的图片:

初始屏幕 初始屏幕

经过一番淘选 经过一番淘选

缩小并再次放大后 缩小并再次放大后

如何解决这个问题?我试图实现我自己的渲染器,但它的情况相同.就像overaly缓存一样,它不会按时重绘.我正在从iOS SDK 10 xCode 8开始使用iOS 10,iPhone 6,模拟器.

小智 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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