1. 程式人生 > >改變MKAnnotationView的大小,使之隨MKMapView的縮放而縮放

改變MKAnnotationView的大小,使之隨MKMapView的縮放而縮放

如果要完成如題功能,有一個技術點需要實現。就是如何detect KMapView的pinch事件, iOS中有UIPinchGestureRecognizer,所以我們可以用這個來detect.

首先向MKMapView加一個gesture recognizer, 如下程式碼:

  1. UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];  
  2. [pinchGesture setDelegate:self];  
  3. [mapView addGestureRecognizer:pinchGesture];  
  4. [pinchGesture release];  

一定要在你的controller中實現下面delegate方法,不然會被系統過濾掉,因為MKMapView自己有系統的pinch Gesture recognizer。

  1. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer  
  2. {  
  3.     return YES;  
  4. }  

然後就在回撥方法中實現:
  1. - (void)handlePinchGesture:(UIGestureRecognizer *)gesture  
  2. {  
  3.     if (gesture.state != UIGestureRecognizerStateChanged) {  
  4.         return;  
  5.     }  
  6.     [self refreshAnnotationView];  
  7. }  

其中refreshAnnotationView程式碼如下,找mapView中所有的annotationView,並更新大小
  1. - (void)refreshAnnotationView  
  2. {      
  3.     for (id <MKAnnotation>annotation in _mapView.annotations) {  
  4.         if ([annotation isKindOfClass:[MKAnnotation class]])  
  5.         {  
  6.             MKAnnotationView *pinView = [_mapView viewForAnnotation:annotation];  
  7.             [self formatAnnotationView:pinView];  
  8.             double zoomLevel = [_mapView getZoomLevel];  
  9.             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
  10.             pinView.transform = CGAffineTransformMakeScale(scale, scale);  
  11.         }  
  12.     }   
  13. }  
其中getZoomLevel是MKMapView的一個category方法,它可以獲取當前地圖的縮放等級,在以這兒有介紹。