Resize MKAnnotationView Image When map zooms in and out?

前端 未结 5 623
误落风尘
误落风尘 2020-12-05 08:50

What i have

I have about 150 MKAnnotationViews on a map. Every MKAnnotationView has an image that replaces the default pin.

What\'s

5条回答
  •  难免孤独
    2020-12-05 09:48

    @Funktional's answer in Swift 3:

    class MapViewController: UIViewController: UIGestureRecognizerDelegate {
    
        @IBOutlet weak var mapView: MKMapView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // You can also add this gesture recognizer and set the delegate via storyboard
            let pinchGR = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchGesture))
            pinchGR.delegate = self
            self.mapView.addGestureRecognizer(pinchGR)
        }
    
        // link as @IBAction when added via storyboard
        func handlePinchGesture(_ sender: UIPinchGestureRecognizer) {
            if sender.state == .ended {
                for annotation in mapView.annotations {
                    if annotation is MKUserLocation {
                        continue
                    }
                    guard let annotationView = self.mapView.view(for: annotation) else { continue }
                    let scale = -1 * sqrt(1 - pow(mapView.zoomLevel / 20, 2.0)) + 1.4
                    annotationView.transform = CGAffineTransform(scaleX: CGFloat(scale), y: CGFloat(scale))
                }
            }
        }
    
        func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
            return true
        }
    }
    
    extension MKMapView {
        var zoomLevel: Double {
            return log2(360 * ((Double(self.frame.size.width) / 256) / self.region.span.longitudeDelta)) - 1
        }
    }
    

提交回复
热议问题