1

我用这段代码画线:

 - (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方法,我没有得到触摸是否属于我的线路路径。

4

2 回答 2

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  
}   

}
于 2012-02-10T08:41:28.613 回答
0

如果路径只是一条线,不确定是否可以获得接触点。如果它是一个数字,我相信你能明白这一点。我想也许你应该将你的观点转换为你的图层。接触点在您的 UIView 中。我正在编写一些使用“CAShapeLayer 和接触点”的代码。也许它可以帮助你。https://github.com/pyanfield/WSChart/blob/master/WSCharts/WSPieChartWithMotionView.m

于 2012-02-14T07:45:40.247 回答