Search code examples
iphoneobjective-ciosuitouchcashapelayer

Get Touch point in CAShapelayer


i am drawing line by this code:

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

}

now i want to know when my line goes touches. how is it possible ? i am using

- (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..");
        }  
    }

} but by CGPathContainsPoint method i am not getting that touch is belongs to my line path or not.


Solution

  • The following code worked for me

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