我有一个任意的CGPath
,我想找到它的地理中心。我可以得到路径边界框,CGPathGetPathBoundingBox
然后找到该框的中心。但是有没有更好的方法来找到路径的中心?
喜欢看代码的人更新:这里是使用 Adam 在答案中建议的平均点法的代码(不要错过下面答案中更好的技术)......
BOOL moved = NO; // the first coord should be a move, the rest add lines
CGPoint total = CGPointZero;
for (NSDictionary *coord in [polygon objectForKey:@"coordinates"]) {
CGPoint point = CGPointMake([(NSNumber *)[coord objectForKey:@"x"] floatValue],
[(NSNumber *)[coord objectForKey:@"y"] floatValue]);
if (moved) {
CGContextAddLineToPoint(context, point.x, point.y);
// calculate totals of x and y to help find the center later
// skip the first "move" point since it is repeated at the end in this data
total.x = total.x + point.x;
total.y = total.y + point.y;
} else {
CGContextMoveToPoint(context, point.x, point.y);
moved = YES; // we only move once, then we add lines
}
}
// the center is the average of the total points
CGPoint center = CGPointMake(total.x / ([[polygon objectForKey:@"coordinates"] count]-1), total.y / ([[polygon objectForKey:@"coordinates"] count]-1));
如果你有更好的想法,请分享!