SwiftUI:如何生成具有透明背景的地图路线?

SwiftUI: How to generate a Map Route with transparent background?

我正在尝试创建一个显示锻炼路线的地图,但我在 MapKit 文档中找不到任何关于如何自定义背景的信息,即在这里我希望地图本身是透明的这样只有路线(注释)是可见的。我该怎么做?

struct MapOverlay: View {
    
    @ObservedObject var workoutDetailViewModel: WorkoutDetailViewModel
    
    var body: some View {
        if let unwrappedWorkoutLocations = workoutDetailViewModel.fullyLoadedWorkout?.workoutLocations {
            Map(
                coordinateRegion: .constant(
                    MKCoordinateRegion(
                        center: unwrappedWorkoutLocations.map {[=10=].coordinate}.center(), // Use the midpoint of the workout as the centre of the map.
                        span: MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
                    )
                ),
                annotationItems: unwrappedWorkoutLocations.map {[=10=].coordinate}
            ) { routeLocation in
                MapAnnotation(coordinate: routeLocation) {
                    Circle().fill(TrackerConstants.AppleFitnessOrange)
                }
            }
            .cornerRadius(10)
            
        }
    }
}

struct MapOverlay_Previews: PreviewProvider {
    static var previews: some View {
        MapOverlay(workoutDetailViewModel: WorkoutDetailViewModel())
    }
}

不要使用 MKMapView。您想要获取坐标并从中创建一个 UIBezierPath,然后将其渲染到您自己的视图或 UIImage 中。像这个游乐场:

import CoreLocation
import MapKit

let myCoords: [CLLocationCoordinate2D] = [
    .init(latitude: 42.42, longitude: 42.42),
    .init(latitude: 42.43, longitude: 42.425),
    .init(latitude: 42.425, longitude: 42.427),
    .init(latitude: 42.422, longitude: 42.426),
]

let r = MKPolylineRenderer(polyline: .init(coordinates: myCoords, count: myCoords.count))
let path = r.path!

let bezier = UIBezierPath(cgPath: path)
bezier.apply(.init(scaleX: 0.05, y: 0.05))

let renderer = UIGraphicsImageRenderer(bounds: .init(x: 0, y: 0, width: 640, height: 480))
let image = renderer
    .image { context in
        let size = renderer.format.bounds.size

        UIColor.darkGray.setFill()
        context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))

        UIColor.black.setStroke()
        bezier.lineWidth = 5
        bezier.stroke()
}