【问题标题】:How to create circle with radius in kilometers with swiftui and mapkit where you can change the radius size with a slider?如何使用 swiftui 和 mapkit 创建半径为公里的圆,您可以在其中使用滑块更改半径大小?
【发布时间】:2023-02-06 00:25:03
【问题描述】:

我一直在努力为我的问题找到一个清晰而简单的答案。所以我想与面临同样问题的每个人分享解决方案。我试图用 swiftui 在地图中创建一个圆圈。我无法使用滑块更新此圈子。滑块用于更改以千米为单位的半径大小。

我在网上搜索了很多。但大多数时候都是旧式或复杂的。

【问题讨论】:

    标签: swiftui slider mapkit radius mkcircle


    【解决方案1】:

    我的解决方案

    import SwiftUI
    import MapKit
    
    class CustomCircleRenderer: MKCircleRenderer {
        override var fillColor: UIColor {
            get {
                return UIColor.red.withAlphaComponent(0.4)
            }
            set {
                super.fillColor = newValue
            }
        }
    }
    
    struct MapView: UIViewRepresentable {
        @Binding var radius: Double
    
        func makeUIView(context: Context) -> MKMapView {
            let mapView = MKMapView()
            mapView.delegate = context.coordinator
            return mapView
        }
    
        func updateUIView(_ uiView: MKMapView, context: Context) {
            uiView.removeOverlays(uiView.overlays)
    
            let center = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194)
            let region = MKCoordinateRegion(center: center, latitudinalMeters: radius, longitudinalMeters: radius)
            uiView.setRegion(region, animated: true)
    
            let circle = MKCircle(center: center, radius: radius)
            uiView.addOverlay(circle)
        }
    
        func makeCoordinator() -> Coordinator {
            Coordinator(self)
        }
    
        class Coordinator: NSObject, MKMapViewDelegate {
            var parent: MapView
    
            init(_ parent: MapView) {
                self.parent = parent
            }
    
            func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
                let renderer = CustomCircleRenderer(overlay: overlay)
                return renderer
            }
        }
    }
    
    struct MapCircleView: View {
        @State var radius: Double = 10000
    
        var body: some View {
            VStack {
                MapView(radius: $radius)
                    .frame(height: 300)
    
                Slider(value: $radius, in: 1000...20000, step: 1000)
                    .padding()
            }
        }
    }

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2021-04-15
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多