如何绘制和与UIBezierPath交互

我想在我的应用程序中实现和devise一个build筑物地板的地图。 在开始之前,我想提供一些build议。

我打算使用UIBezierPath来绘制形状。 每个UIBezierPath将在我的地图上代表一家商店。 这里是一个插图( map_with_UIBezierPath )

我的代码结构如下:我有一个UIViewController和一个UiView。 在UIViewController“viewDidLoad”方法中,我实例化UIView,并在UIView“drawRect”方法中,绘制如下形状(UIBezierPathExtension从UIBezierPathinheritance):

- (void)drawRect:(CGRect)rect { context = UIGraphicsGetCurrentContext(); [[UIColor grayColor] setFill]; [[UIColor greenColor] setStroke]; UIBezierPathExtension *aPath = [[UIBezierPathExtension alloc] init]; aPath.pathId = 1; [aPath moveToPoint:CGPointMake(227,34.25)]; [aPath addLineToPoint:CGPointMake(298.25,34.75)]; [aPath addLineToPoint:CGPointMake(298.5,82.5)]; [aPath addLineToPoint:CGPointMake(251,83)]; [aPath addLineToPoint:CGPointMake(251,67.5)]; [aPath addLineToPoint:CGPointMake(227.25,66.75)]; [aPath closePath]; aPath.lineWidth = 2; [aPath fill]; [aPath stroke]; [paths addObject:aPath]; UIBezierPathExtension* aPath2 = [[UIBezierPathExtension alloc] init]; aPath2.pathId = 2; [aPath2 moveToPoint:CGPointMake(251.25,90.5)]; [aPath2 addLineToPoint:CGPointMake(250.75,83.25)]; [aPath2 addLineToPoint:CGPointMake(298.5,83)]; [aPath2 addLineToPoint:CGPointMake(298.5,90.25)]; [aPath2 closePath]; aPath2.lineWidth = 2; [aPath2 fill]; [aPath2 stroke]; [paths addObject:aPath2]; ... } 

我也在UIViewController中实现了平移和捏合手势。

现在,我问我如何与每一个形状互动。 我想检测一下,点击它,改变他的颜色,并显示一个类似于选定形状的菜单。

有人能告诉我正确的方向吗?

Thx提前

您需要在视图中查找触摸事件(TouchesBegan,TouchesMoved,TouchesEnded,TouchesCancelled)。 当你接触到的时候,你可以问你在视图中的位置。 你可以使用这个位置来testing这个点是否在你的任何path之内,如果是的话,做你的酷东西。

使用你的示例代码,这里可能是一个粗糙的TouchesBegan …

 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { CGPoint pointTouched = [touch locationInView:self]; for (UIBezierPath *path in paths) { if ([path containsPoint:point]) { // do something cool with your path // or more likely, set a flag to do the cool thing when drawing } } } } 

不要忘记,你应该处理所有触摸事件,并做一些明智的事情。 另外,上面的代码具有多点触控function,但是您可能只想要一次触摸,在这种情况下,有办法消除“触摸”循环。