2012-02-10 44 views
1

我對這個代碼畫線:獲取觸摸點在CAShapelayer

- (void) drawLine:(float)x :(float)y:(float)toX:(float)toY 
{ 
CAShapeLayer *lineShape = nil; 
CGMutablePathRef linePath = nil; 
linePath = CGPathCreateMutable(); 
lineShape = [CAShapeLayer layer]; 

lineShape.lineWidth = 1.0f; 
lineShape.lineCap = kCALineJoinMiter; 
lineShape.strokeColor = [[UIColor redColor] CGColor]; 


CGPathMoveToPoint(linePath, NULL, x, y); 
CGPathAddLineToPoint(linePath, NULL, toX, toY); 

lineShape.path = linePath; 
CGPathRelease(linePath); 

if(x != 0 && y != 0) 
[myView.layer addSublayer:lineShape]; 

}

現在我想知道當我行雲觸摸。這怎麼可能 ? 我使用

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 

NSIndexSet *indexSet = [myView.layer.sublayers indexesOfObjectsPassingTest:^(id obj,  NSUInteger idx, BOOL *stop){ 
     return [obj isMemberOfClass:[CAShapeLayer class]]; 
    }]; 

    NSArray *textLayers = [myView.layer.sublayers objectsAtIndexes:indexSet]; 
    for (CAShapeLayer *textLayer in textLayers) { 
     CGPoint p = [[touches anyObject] locationInView:myView]; 
     NSLog(@"touch x is :%f",p.x); 

     CGAffineTransform transf = CGAffineTransformMakeTranslation(-textLayer.position.x, - textLayer.position.y); 

     if(CGPathContainsPoint(textLayer.path, &transf, p, NO)){  
      NSLog(@"touched.."); 
     } 
    } 

} 但CGPathContainsPoint方法我沒有得到那一抹是屬於我行路徑或沒有。

+0

我認爲這是因爲你的滾動視圖的內容偏移。 – Vignesh 2012-02-10 07:31:29

+0

Y你會做CGAffineTransformMakeTranslation(-textLayer.position.x, - textLayer.position.y)嗎?事實上,它沒有改造就適合我。 – Vignesh 2012-02-10 07:37:01

+0

那我寫了什麼代碼? – PJR 2012-02-10 08:34:03

回答

3

下面的代碼爲我工作

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 

CGPoint p = [[touches anyObject] locationInView:self.view]; 

if(CGPathContainsPoint(textLayer.path,nil, p, NO)) 
{  

    NSLog(@"touched"); 
    // the touch is inside the shape 
} 

} 
+0

我已經試過這個,但它不工作。當我接觸線時,什麼也沒有發生。 – PJR 2012-02-10 09:18:04

+0

不考慮線寬 – jjxtra 2013-12-08 20:31:49