【问题标题】:Resize MKAnnotationView with MKZoomScale - Swift 2.0使用 MKZoomScale 调整 MKAnnotationView 的大小 - Swift 2.0
【发布时间】:2016-09-24 19:44:22
【问题描述】:

我正在尝试制作可调整大小的注释

我创建了一个自定义注释

class MapAnnotation: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var image: UIImage? = UIImage(named: "image")

    init(coordinate: CLLocationCoordinate2D) {
        self.coordinate = coordinate
    }
}

以及包含图像的 annotationView。

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if let annotation = annotation as? MapAnnotation {
        var pin = mapView.dequeueReusableAnnotationViewWithIdentifier("myCustomAnnotation")
        if pin == nil {
            pin = MKAnnotationView(annotation: annotation, reuseIdentifier: "myCustomAnnotation")
        }
        pin!.image = annotation.image
        return pin
    }
    return nil
}

当我调整 mapView 的大小时,我希望 MKAnnotationView 也将调整大小。

我知道 MKOverlayRenderer 有 drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext) 函数,其中包含 zoomScale: MKZoomScale 参数。

此外,我看到了这个解决方案:

let zoomScale: MKZoomScale = mapView.bounds.size.width /
        CGFloat(mapView.visibleMapRect.size.width)

但我希望在drawMapRect 函数中访问MKZoomScale 而不是自定义方式。

这意味着我需要制作一个 MKOverlayRenderer 而不是我不想制作的 MKAnnotationView,因为 MKOverlay 正在地图上绘制,而我想制作一个未在地图上绘制的 annotationView。

之后我将拥有 MKZoomScale,我想在 MKZoomScale 1 到 0.25 之间调整 annotationViews 的大小,如果 MKZoomScale 低于 0.25,我希望 annotationViews 消失。

感谢您的帮助!

【问题讨论】:

    标签: ios swift mapkit mkannotation mkoverlay


    【解决方案1】:

    您可以从 mapView 的区域变量的 span 中获取“缩放”量:

    mapView.region.span
    

    然后,在您的 viewForAnnotation 函数中,您可以做一些数学运算来缩放注释,或者让注释对自身执行某种功能以显示更大。

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    <pin init methods>
    let averageSpan = mapView.region.span.x * mapView.region.span.x * 0.5
    let pinScale = someFunctionToReturnScaleBasedOnAverageSpan(averageSpan)
    pin.scaleSelf(pinScale)
    return pin
    

    }

    我不记得了,但是如果 viewForAnnotation 在地图更新其跨度时没有被调用,您需要某种更新函数来删除和添加注释。

    不过,使用 MKOverlay 会更容易。

    【讨论】:

    • 只是函数drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext) 中的MKZoomScale 为您提供了我想使用的默认缩放比例。如果我想使用 MKCoordinateSpan,我已经使用它了。您可以尝试使用函数drawMapRect 并打印zoomScale,这样您就可以看到我在说什么了。
    猜你喜欢
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多