如何绘制UIBezierPath并与之交互

问题描述:

我想在我的应用程序中实现和设计建筑物地板的地图。在开始之前,我想提供一些建议。如何绘制UIBezierPath并与之交互

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

我的代码结构如下:我有一个UIViewController和一个UiView。在UIViewController的“viewDidLoad中”的方法,我实例化的UIView和UIView的“的drawRect”的方法,我得出的形状像以下(UIBezierPathExtension从UIBezierPath继承):

- (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中。

现在,我问我如何与每一个形状交互。我想检测一下它,改变他的颜色并在选定的形状上显示一个像that这样的菜单。

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

THX提前

您需要寻找您的视图触摸事件(的touchesBegan,TouchesMoved,TouchesEnded,TouchesCancelled)。当你接触时,你可以在视图中询问它的位置。你可以使用这个位置来测试这个点是否在你的任何路径之内,如果是的话,做你喜欢的东西。

使用您的示例代码,这里可能是一个粗略的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 
      } 
     } 
    } 
} 

不要忘记,你应该处理所有的触摸事件,做一些理智的对待每一个。此外,上面的代码具有多点触控功能,但您可能只想进行一次触控,在这种情况下,您可以通过多种方式来消除“触控”循环。