是CGPoint在MKPolygonView?

时间:2013-01-25 15:14:50

标签: ios mkoverlay

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

1 个答案:

答案 0 :(得分: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];

}