任意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));
より良いアイデアがあれば、共有してください!