我希望用户能够在 map 中放置一些(未知数量的)MKpointAnnotations 后创建多边形。我已经放置了一个手势识别器,一旦用户点击一个按钮就会激活它,因此放置了注释。但是如何使用这些作为 MKPolygon 的角? 在保存多边形角的代码下面。这是在我对它做了一些修改之后。现在应用程序崩溃了,崩溃报告器说索引超出范围。角是通过 GestureRecognizer 创建的 MKPointAnnotation-s。
-(IBAction)addCorner:(id)sender
{
NSMutableArray *addCorners = [[NSMutableArray alloc] init];
[addCorners addObject:pointAnnotation];
ptsArray = addCorners;
}
-(IBAction)addPolygonOverlay:(id)sender
{
int cornersNumber = sizeof(ptsArray);
MKMapPoint points[cornersNumber];
for (int i=0; i<cornersNumber; i++) {
points[i] = MKMapPointForCoordinate([[ptsArray objectAtIndex:i] coordinate]);
}
MKPolygon *polygon = [MKPolygon polygonWithPoints:points count:cornersNumber];
[mapview addOverlay:polygon];
}
最佳答案
第一个问题是 addCorner
方法。它不是将每个角都添加到 ptsArray
变量,而是创建一个仅包含最后一个角的新数组,并将 ptsArray
设置为等于该值,因此它只有一个,即最后一个角.
像这样更改 addCorner
方法:
-(IBAction)addCorner:(id)sender
{
if (ptsArray == nil)
{
self.ptsArray = [NSMutableArray array];
}
[ptsArray addObject:pointAnnotation];
}
还要确保 ptsArray
已正确声明和合成:
//in the .h file...
@property (nonatomic, retain) NSMutableArray *ptsArray;
//in the .m file...
@synthesize ptsArray;
(顺便说一句,为什么不在创建 pointAnnotation
的地方将角添加到 ptsArray
而不是在单独的用户操作中?)
第二个问题在 addPolygonOverlay
方法中。您必须使用 NSArray
count
属性来获取数组中的项数。 sizeof
函数返回传递的变量使用的物理内存的字节数。 ptsArray
是一个指针,它会返回4。如果ptsArray
少于4项,你会得到“index out of range”异常。
所以改变
int cornersNumber = sizeof(ptsArray);
到
int cornersNumber = ptsArray.count;
另一个需要注意的重要事项是多边形边将按照点在数组中的顺序绘制。如果用户不按顺时针或逆时针顺序添加角,多边形看起来会很奇怪。您可以在用户添加/删除注释后立即重新创建多边形叠加层,以便他们立即获得有关其外观的反馈。
关于iphone - 从 map 中用户放置的注释创建 MKPolygon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7955534/