2012-04-14 11 views
8

Ho creato un grafico a ragno facendo un overect draw rect, sto usando core grahics CAShapeLayer per disegnare le mie aree, ci sono più regioni CAShapeLayer che vengono create sullo schermo, voglio rilevare quale layer viene toccato quando gli utenti toccano ... ma non riesco a capire come?rileva CAShapeLayer touch

risposta

16

Per prima cosa, non devi disegnare i livelli in drawRect, ma non è questa la tua domanda. Per identificare un layer che viene "toccato" si può fare qualcosa di simile ...

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

Ciao Jody, si può semplicemente ampliare il codice all'interno del se la condizione per più luce, – user1333444

+0

OK, ho aggiornato con un po ' più dettaglio. In sostanza, se si tratta di un livello forma, si interroga il suo percorso e si vede se quel percorso contiene il punto ... Si noti, tuttavia, che è necessario passare il tipo di riempimento come parte del CGPathContainsPoint - Ho assunto pari/dispari. Usa tutto ciò che ti serve ... –

+0

Questo non funziona per i tocchi sul bordo se la larghezza della linea è maggiore di 1. – jjxtra