[英]SwiftUI: How to generate a Map Route with transparent background?
我正在嘗試創建一個 map 來顯示鍛煉路線,但我在 MapKit 文檔中找不到任何關於如何自定義背景的信息,即在這里我希望 map 本身是透明的,以便只有路線(注釋)是可見的。 我怎樣才能做到這一點?
struct MapOverlay: View {
@ObservedObject var workoutDetailViewModel: WorkoutDetailViewModel
var body: some View {
if let unwrappedWorkoutLocations = workoutDetailViewModel.fullyLoadedWorkout?.workoutLocations {
Map(
coordinateRegion: .constant(
MKCoordinateRegion(
center: unwrappedWorkoutLocations.map {$0.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 {$0.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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.