如果要完成如题功能,有一个技术点需要实现。就是如何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);
- }
- }
- }