0

我试图找出一种方法来检测哪个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,但结果更糟。

4

1 回答 1

1

感谢@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];

}
于 2013-01-25T16:47:17.417 回答