改變MKAnnotationView的大小,使之隨MKMapView的縮放而縮放
阿新 • • 發佈:2019-02-14
如果要完成如題功能,有一個技術點需要實現。就是如何detect KMapView的pinch事件, iOS中有UIPinchGestureRecognizer,所以我們可以用這個來detect.
首先向MKMapView加一個gesture recognizer, 如下程式碼:
- UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
- [pinchGesture setDelegate:self];
- [mapView addGestureRecognizer:pinchGesture];
- [pinchGesture release];
一定要在你的controller中實現下面delegate方法,不然會被系統過濾掉,因為MKMapView自己有系統的pinch Gesture recognizer。
- - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
- {
- return YES;
- }
然後就在回撥方法中實現:
- - (void)handlePinchGesture:(UIGestureRecognizer *)gesture
- {
- if (gesture.state != UIGestureRecognizerStateChanged) {
- return;
- }
- [self refreshAnnotationView];
- }
其中refreshAnnotationView程式碼如下,找mapView中所有的annotationView,並更新大小
- - (void)refreshAnnotationView
- {
- for (id <MKAnnotation>annotation in _mapView.annotations) {
- if ([annotation isKindOfClass:[MKAnnotation class]])
- {
- MKAnnotationView *pinView = [_mapView viewForAnnotation:annotation];
- [self formatAnnotationView:pinView];
- double zoomLevel = [_mapView getZoomLevel];
- double scale = -1 * sqrt((double)(1 - pow((zoomLevel/16.0), 2.0))) + 2.0; // This is a circular scale function where at zoom level 0 scale is 0.1 and at zoom level 20 scale is 1.1
- pinView.transform = CGAffineTransformMakeScale(scale, scale);
- }
- }
- }