1

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.

PJR
  • 13,052
  • 13
  • 64
  • 104

2 Answers2

3

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  
}   

}
Vignesh
  • 10,205
  • 2
  • 35
  • 73
0

not sure if you can get the touch point if the path is only a line. if it is a figure, I'm sure you can get that point. I think maybe you should convert your point to your layer. the touch point is in your UIView. I'm writing some code that uses "CAShapeLayer and touch point". Maybe it can help you. https://github.com/pyanfield/WSChart/blob/master/WSCharts/WSPieChartWithMotionView.m

pyanfield
  • 479
  • 6
  • 19