有没有办法在苹果地图上增加一个边框呢?
P.S
只是想分享一个解决方案
发布于 2019-11-12 02:08:21
我的实现是在主lineWidth
下面添加另一个polyline覆盖,它将比主像素厚几个像素(您的边框宽度可以说)。
// Instantiate the main polyline
let polylineObj = MKPolyline(coordinates: yourArrayOfCoords, count: yourArrayOfCoords.count)
// Identifier to tell which is which
polylineObj.title = "main"
// Instantiate the border polyline
let borderPolylineObj = MKPolyline(coordinates: yourArrayOfCoords, count: yourArrayOfCoords.count)
// Add main polyline
appleMapView.addOverlay(polylineObj)
// Add border polyline below the main polyline
appleMapView.insertOverlay(borderPolylineObj, below: polylineObj)
然后在MKMapViewDelegate
函数上:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
// Use different colors for the border and the main polyline
renderer.strokeColor = overlay.title == "main" ? .blue : .red
// Make the border polyline bigger. Their difference will be like the borderWidth of the main polyline
renderer.lineWidth = overlay.title == "main" ? 4 : 6
// Other polyline customizations
renderer.lineCap = .round
renderer.lineJoin = .bevel
return renderer
}
P.S
如果你有一个更好的实现,请做回答。这个实现是昂贵的,因为这将基本上是呈现的polyline数量的两倍。
发布于 2022-10-07 10:44:13
public class BorderPathRenderer: MKOverlayPathRenderer {
var polyline: MKPolyline
var color: UIColor
var showsBorder: Bool = false
var borderColor: UIColor = .black
public init(polyline: MKPolyline, color: UIColor) {
self.polyline = polyline
self.color = color
super.init(overlay: polyline)
}
public init(polyline: MKPolyline, color: UIColor, showsBorder: Bool, borderColor: UIColor) {
self.polyline = polyline
self.color = color
self.showsBorder = showsBorder
self.borderColor = borderColor
super.init(overlay: polyline)
}
public override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
let baseWidth: CGFloat = lineWidth / zoomScale
if showsBorder {
context.setLineWidth(baseWidth * 2)
context.setLineJoin(CGLineJoin.round)
context.setLineCap(CGLineCap.round)
context.addPath(path)
context.setStrokeColor(borderColor.cgColor)
context.strokePath()
}
context.setLineWidth(baseWidth)
context.addPath(path)
context.setStrokeColor(color.cgColor)
context.strokePath()
super.draw(mapRect, zoomScale: zoomScale, in: context)
}
public override func createPath() {
let path: CGMutablePath = CGMutablePath()
var pathIsEmpty: Bool = true
for i in 0...self.polyline.pointCount - 1 {
let point: CGPoint = self.point(for: self.polyline.points()[i])
if pathIsEmpty {
path.move(to: point)
pathIsEmpty = false
} else {
path.addLine(to: point)
}
}
self.path = path
}
}
https://stackoverflow.com/questions/58810993
复制相似问题