How to create CGPathRef from Array of points

2020-05-27 07:33发布

问题:

Hi all i've been working in a map application, Where i needed to draw the route between two locations, I've got route coordinates too (using google Direction api) and kept it in an array, Now all i need to do is creating a path from the array of points, later i will use the path with MKOverlayPathView for creating real routes on the map. Here my problem is how to create a CGPathRef from the array of coordinates, Or any other way to do the same operation
Thanks in Advance

回答1:

Assuming the coordinates are stored in an NSArray as NSValue objects, you can do the following:

CGMutablePathRef path = CGPathCreateMutable();
if (points && points.count > 0) {
    CGPoint p = [(NSValue *)[points objectAtIndex:0] CGPointValue];
    CGPathMoveToPoint(path, nil, p.x, p.y);
    for (int i = 1; i < points.count; i++) {
        p = [(NSValue *)[points objectAtIndex:i] CGPointValue];
        CGPathAddLineToPoint(path, nil, p.x, p.y);
    }
}
// do stuff
CGPathRelease(path);


回答2:

Another way to create path:

CGPoint points[5];
// TODO: Fill points array with values.
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddLines(path, NULL, points, 5);
// TODO: Do something useful with path.
CGPathCloseSubpath(path);
CGPathRelease(path);