ios - MapKit中缩放相关的MKPolyline奇怪渲染

标签 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

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

最佳答案

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 委托(delegate)中使用它:

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

您的多段线在缩放后不会重新渲染,从而避免了伪影

关于ios - MapKit中缩放相关的MKPolyline奇怪渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40238370/

相关文章:

ios - 如何在按钮函数中传递特定函数的常量值以将其用作导航目的地

ios - map 注释重用

ios - WKWebView drawViewHierarchyInRect 不会在手机上呈现 webGL 内容

ios - 放松 segue 干扰 shoe segue

ios - swift Eureka : Can't dynamically hide/show ButtonRow inside cellUpdate

ios - 将核心数据数据库从一个应用程序迁移到另一个应用程序

ios - 使用特定的 MKRoute 信息打开 Apple Maps 应用程序

iphone - 在 iTunesConnect 上添加应用程序购买只允许免费订阅

ios - 具有 UIDocumentPickerModeOpen 模式的 UIDocumentPickerViewController 未授予在 xcode 中编辑文件的权限(iOS)

ios - 每次我的应用程序从后台返回时,我都需要向方法发送一条消息