在CGPolygonView CGPoint?

我试图找出一种方法来检测哪个MKOverlayView (实际上MKPolygonView )被挖掘,然后改变它的颜色。

我得到它与这个代码运行:

 - (void)mapTapped:(UITapGestureRecognizer *)recognizer { MKMapView *mapView = (MKMapView *)recognizer.view; MKPolygonView *tappedOverlay = nil; for (id<MKOverlay> overlay in mapView.overlays) { MKPolygonView *view = (MKPolygonView *)[mapView viewForOverlay:overlay]; if (view){ // Get view frame rect in the mapView's coordinate system CGRect viewFrameInMapView = [view.superview convertRect:view.frame toView:mapView]; // Get touch point in the mapView's coordinate system CGPoint point = [recognizer locationInView:mapView]; // Check if the touch is within the view bounds if (CGRectContainsPoint(viewFrameInMapView, point)) { tappedOverlay = view; break; } } } if([[tappedOverlay fillColor] isEqual:[[UIColor cyanColor] colorWithAlphaComponent:0.2]]){ [listOverlays addObject:tappedOverlay]; tappedOverlay.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.2]; } else{ [listOverlays removeObject:tappedOverlay]; tappedOverlay.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.2]; } //tappedOverlay.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7]; } 

哪些工作,但有时,取决于我点击它得到错误哪个MKPolygonView被挖掘。 我想因为CGRectContainsPoint正确计算面积,因为它不是一个矩形,它是一个多边形。

还有什么其他的方法可以做到这一点? 我试过CGPathContainsPoint但我得到更糟糕的结果。

感谢@Ana Karenina,指出了正确的方法,这就是你如何转换手势,使方法CGPathContainsPoint “正确的工作。

 - (void)mapTapped:(UITapGestureRecognizer *)recognizer{ MKMapView *mapView = (MKMapView *)recognizer.view; MKPolygonView *tappedOverlay = nil; int i = 0; for (id<MKOverlay> overlay in mapView.overlays) { MKPolygonView *view = (MKPolygonView *)[mapView viewForOverlay:overlay]; if (view){ CGPoint touchPoint = [recognizer locationInView:mapView]; CLLocationCoordinate2D touchMapCoordinate = [mapView convertPoint:touchPoint toCoordinateFromView:mapView]; MKMapPoint mapPoint = MKMapPointForCoordinate(touchMapCoordinate); CGPoint polygonViewPoint = [view pointForMapPoint:mapPoint]; if(CGPathContainsPoint(view.path, NULL, polygonViewPoint, NO)){ tappedOverlay = view; tappedOverlay.tag = i; break; } } i++; } if([[tappedOverlay fillColor] isEqual:[[UIColor cyanColor] colorWithAlphaComponent:0.2]]){ [listOverlays addObject:tappedOverlay]; tappedOverlay.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.2]; } else{ [listOverlays removeObject:tappedOverlay]; tappedOverlay.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:0.2]; } //tappedOverlay.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7]; }