2012-04-14 113 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