如何在 SwiftUI / Mapkit 中正确显示自定义图钉?

How do you properly display custom pins in SwiftUI / Mapkit?

我正在构建依赖于 MapKit 的 SwiftUI 应用程序。

但我遇到了自定义图钉标记的呈现问题。

每当我添加 pin 时,它都是从图像的中心渲染的,因此它不会与当前位置正确对齐。

我试过添加偏移量,改变原点,但自定义图钉图像基本上超出范围。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let view = MKAnnotationView(annotation: annotation, reuseIdentifier: nil)
    let size = CGSize(width: 35, height: 40)
    UIGraphicsBeginImageContext(size)
    UIImage(named: "customPin")?.draw(in: CGRect(origin: CGPoint(x: 0, y: 20), size: size))
    
    //let context = UIGraphicsGetCurrentContext()!
    //context.move(to: CGPoint(x:0, y: -200))
    // This code didn't affect the rendering
    
    view.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    view.canShowCallout = true
    return view
}

基本上我认为正在发生的事情是我正在应用的偏移正在移动图像,但 CGRect 的边界保持在同一个位置。我不知道如何抵消两者。

在 Apple 的文档中:Annotating a Map with Custom Data 他们提供了以下示例代码:

private func setupSanFranciscoAnnotationView(for annotation: SanFranciscoAnnotation, on mapView: MKMapView) -> MKAnnotationView {
   let reuseIdentifier = NSStringFromClass(SanFranciscoAnnotation.self)
   let flagAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier, for: annotation)

   flagAnnotationView.canShowCallout = true

   // Provide the annotation view's image.
   let image = #imageLiteral(resourceName: "flag")
   flagAnnotationView.image = image

   // Provide the left image icon for the annotation.
   flagAnnotationView.leftCalloutAccessoryView = UIImageView(image: #imageLiteral(resourceName: "sf_icon"))

   // Offset the flag annotation so that the flag pole rests on the map coordinate.
   let offset = CGPoint(x: image.size.width / 2, y: -(image.size.height / 2) )
   flagAnnotationView.centerOffset = offset
    
   return flagAnnotationView
}

他们正在使用 centerOffset 重新定位 image/annotation。你试过这个吗?他们已经将图像向上和向右移动,因为他们想要将一个角与坐标对齐,通常我只想要中心底部对齐,所以为 x 偏移量提供零。