mbrmj
mbrmj

Reputation: 129

How can I use CGContextPathContainsPoint() to detect a point?

I used this function to draw a path between two points. I get the coordinates from Google's API, and there's no problem with this. My problem is, how can I specify whether a particular point is within the path I draw or not? I'm trying to use CGContextPathContainsPoint(), but with no luck.

-(void)updateRouteView {
    CGContextRef context =  CGBitmapContextCreate(nil,
                                                 routeView.frame.size.width,
                                                 routeView.frame.size.height,
                                                 8,
                                                 4 * routeView.frame.size.width,
                                                 CGColorSpaceCreateDeviceRGB(),
                                                 kCGImageAlphaPremultipliedLast);

    CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
    CGContextSetLineWidth(context, 5.0);

    // routes : array of coordinates of the path
    for (int i = 0; i < routes.count; i++) {
        CLLocation* location = [routes objectAtIndex:i];
        CGPoint point = [mapView convertCoordinate:location.coordinate toPointToView:routeView];

        if (i == 0)
            CGContextMoveToPoint(context, point.x, routeView.frame.size.height - point.y);
        else
            CGContextAddLineToPoint(context, point.x, routeView.frame.size.height - point.y);
    }

    CGContextStrokePath(context);

    // this is the point I want to check if it is inside the path
    CLLocationCoordinate2D checkedLocation;
    checkedLocation.latitude = 37.782756;
    checkedLocation.longitude =  -122.409647;
    CGPoint checkedPoint = [mapView convertCoordinate:checkedLocation toPointToView:routeView];
    checkedPoint.y = routeView.frame.size.height - checkedPoint.y;

    // even if the checkedPoint is inside the path, the result is false    
    BOOL checking = CGContextPathContainsPoint(context, checkedPoint, kCGPathStroke);
    if (checking)
        NSLog(@"YES");
    else
        NSLog(@"NO");

    CGImageRef image = CGBitmapContextCreateImage(context);
    UIImage* img = [UIImage imageWithCGImage:image];

    routeView.image = img;
    CGContextRelease(context);
}

Upvotes: 0

Views: 1031

Answers (1)

mprivat
mprivat

Reputation: 21912

Call CGContextStrokePath(context) AFTER you check for your point. Quartz will clear the current path once it's struck.

Upvotes: 3

Related Questions