我有非常简单的 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
}
}
折线的渲染很奇怪。在缩放和平移期间,您会看到一些瑕疵。
看看下面的图片:
如何解决这个问题?我试图实现自己的渲染器,但情况相同。就像 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/