【问题标题】:How do you properly display custom pins in SwiftUI / Mapkit?如何在 SwiftUI / Mapkit 中正确显示自定义引脚?
【发布时间】:2021-11-19 02:28:57
【问题描述】:

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

但我在渲染自定义图钉标记时遇到了问题。

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

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

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 的边界保持在同一个位置。我不知道如何抵消两者。

【问题讨论】:

    标签: swift swiftui mapkit mapkitannotation


    【解决方案1】:

    在 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 重新定位图像/注释。你试过这个吗?他们将图像向上和向右移动,因为他们想将角与坐标对齐,通常我只希望中心-底部对齐,因此为 x 偏移提供零。

    【讨论】:

    • 这个我没试过。我会在这个周末检查并报告。谢谢!
    • 谢谢,这正是我所需要的。解决问题的部分是使用 centerOffet。再次感谢!
    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多