2012-04-14 194 views
8

我创建了一个蜘蛛图由overiding画矩形,我使用的核心grahics CAShapeLayer画出我的领域,有其在屏幕上创建多个CAShapeLayer地区,我想检测时,这层被触摸用户接触...但我无法弄清楚如何?检测CAShapeLayer触摸

回答

16

首先,你不应该画在各层drawRect这个,但是这不是你的问题。要识别“感动”,你可以做这样的事情了一层......

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    for (UITouch *touch in touches) { 
     CGPoint touchLocation = [touch locationInView:self.view]; 
     for (id sublayer in self.view.layer.sublayers) { 
      BOOL touchInLayer = NO; 
      if ([sublayer isKindOfClass:[CAShapeLayer class]]) { 
       CAShapeLayer *shapeLayer = sublayer; 
       if (CGPathContainsPoint(shapeLayer.path, 0, touchLocation, YES)) { 
        // This touch is in this shape layer 
        touchInLayer = YES; 
       } 
      } else { 
       CALayer *layer = sublayer; 
       if (CGRectContainsPoint(layer.frame, touchLocation)) { 
        // Touch is in this rectangular layer 
        touchInLayer = YES; 
       } 
      } 
     } 
    } 
} 
+0

嗨乔迪,可你只是扩大if条件里面的代码越轻, – user1333444 2012-04-14 18:22:45

+0

OK,我有一个小更新,它更多详情。基本上,如果它是一个形状图层,则查询它的路径并查看该路径是否包含点...但请注意,您必须将填充类型作为CGPathContainsPoint的一部分传递 - 我假设为偶数/奇数。使用任何你需要的... – 2012-04-14 20:31:50

+0

这不适用于在边境接触的工作,如果线宽大于1 – jjxtra 2013-12-08 20:26:50