您需要在所有 MKMapView 周围绘制一个多边形,其中包含一个内部多边形,该区域是您不想模糊的区域。这是我的解决方案:
首先,您需要坐标来覆盖地图的每一部分:
struct WorldCoordinates {
static let values = [
CLLocationCoordinate2D(latitude: 90, longitude: 0),
CLLocationCoordinate2D(latitude: 90, longitude: 180),
CLLocationCoordinate2D(latitude: -90, longitude: 180),
CLLocationCoordinate2D(latitude: -90, longitude: 0),
CLLocationCoordinate2D(latitude: -90, longitude: -180),
CLLocationCoordinate2D(latitude: 90, longitude: -180)
]
}
然后使用类似这样的方法添加内部和外部多边形:请注意,我使用“City”作为结构的示例,其中 boundigCoordinatesArray 是您不想模糊的区域的边界坐标数组。
func addCityBoundingPolygon(in mapView: MKMapView, with city: City) {
// Declare your inner polygon
let innerPolygon = MKPolygon(coordinates: city.boundingCoordinatesArray, count: city.boundingCoordinatesArray.count)
innerPolygon.title = "\(city.id)"
// Declare your outer polygon with previously created inner polygon
let outerPolygon = MKPolygon(coordinates: WorldCoordinates.values, count: WorldCoordinates.values.count, interiorPolygons: [innerPolygon])
mapView.addOverlay(outerPolygon)
}
最后在 MKMapViewDelegate 上添加外部多边形的颜色,如下所示:
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let polygon = overlay as? MKPolygon {
let renderer = MKPolygonRenderer(polygon: polygon)
renderer.fillColor = UIColor.outOfCityBounds().withAlphaComponent(0.1)
renderer.strokeColor = UIColor.outOfCityBounds().withAlphaComponent(0.4)
renderer.lineWidth = 1
return renderer
}
return MKOverlayRenderer()
}
使用这种方法,您将能够重新创建如下内容: