2012-02-10 105 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