覆盖注释

Overlay around annotation

您好,我正在尝试在我的注释周围创建一个叠加层,例如苹果提醒应用程序,我已经创建了一个 MKCircle 对象,我认为我应该使用它来显示叠加层,但是如何将我的 MKCircle 对象转换为MKOVerlay 对象?也许有更好的方法来添加注释?我是 swift 和编程的新手。有什么建议么?

MKCircle 是一个 MKOverlay 对象。您只需将其添加为叠加层即可:

let circle = MKCircle(center: coordinate, radius: 1000)
mapView.add(circle)

当然,您必须通过在您的委托中实现 mapView(_:rendererFor:) 来告诉地图如何呈现它,并为作为叠加层传递的 MKCircle 实例化一个 MKCircleRenderer

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKCircleRenderer(overlay: overlay)
        renderer.fillColor = UIColor.cyan.withAlphaComponent(0.5)
        renderer.strokeColor = UIColor.cyan.withAlphaComponent(0.8)
        return renderer
    }
}

显然,请确保您也为 MKMapView 指定了 delegate。如果您有其他类型的渲染器,您也可以为它们实现特定的逻辑,例如

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        if let circle = overlay as? MKCircle {
            let renderer = MKCircleRenderer(circle: circle)
            renderer.fillColor = UIColor.cyan.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.cyan.withAlphaComponent(0.8)
            return renderer
        }

        if let polygon = overlay as? MKPolygon {
            let renderer = MKPolygonRenderer(polygon: polygon)
            renderer.fillColor = UIColor.blue.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.blue.withAlphaComponent(0.8)
            return renderer
        }

        if let polyline = overlay as? MKPolyline {
            let renderer = MKPolylineRenderer(polyline: polyline)
            renderer.fillColor = UIColor.red.withAlphaComponent(0.5)
            renderer.strokeColor = UIColor.red.withAlphaComponent(0.8)
            return renderer
        }

        fatalError("Unexpected overlay type")
    }
}