如何使用CGContextPathContainsPoint()来检测点?

时间:2012-04-20 18:33:22

标签: objective-c mkmapview cgcontext

我用这个函数绘制两点之间的路径。我从Google的API获取坐标,这没有问题。我的问题是,如何指定特定点是否在我绘制的路径内?我正在尝试使用CGContextPathContainsPoint(),但没有运气。

-(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);
}

1 个答案:

答案 0 :(得分:3)

在检查您的观点后调用CGContextStrokePath(上下文)。一旦被击中,Quartz将清除当前路径。