0

使用我在互联网上看到的标准代码,我无法检测到对单个 `CAShapeLayer 的触摸。

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

    CGPathRef path = ((CAShapeLayer *)[lettersArray objectAtIndex:1]).path;

    if(CGPathContainsPoint(path, nil, p, NO))
    {
        ((CAShapeLayer *)[lettersArray objectAtIndex:0]).position = p;
        NSLog(@"Touched");
    }

我是否需要至少有一些区域而不仅仅是一个部分?

4

3 回答 3

1

哥们试试这个代码它对我有用

CGPathRef originalPath = shapeView.path;  //The single-line path

//Use the values you use to draw the path onscreen,
//or use a width representing how far the user can touch
//for it to be recognized by the path.
//For example, for an error tolerance of 4px, use a width of 8px.
CGPathRef strokedPath = CGPathCreateCopyByStrokingPath(originalPath, NULL, path.lineWidth, path.lineCapStyle, path.lineJoinStyle, path.miterLimit);
BOOL pathContainsPoint = CGPathContainsPoint(strokedPath, NULL, touchLocation, NO);

NSLog(pathContainsPoint ? @"Yes" : @"No");
于 2015-02-20T10:03:18.953 回答
0

是的,您的路径需要有一些区域供 CGPathContainsPoint 测试一个点是否在其中。您可能想要做的是找到从点到线的距离并测试它是否在某个阈值内。

请注意,该文章中的公式为您提供了到直线而不是线段的距离;如果线上的最近点超出线段的边界,您还需要计算从您的点到线段端点的距离。

于 2013-03-15T00:42:58.227 回答
0
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

for (UITouch *touch in touches) {
    CGPoint touchLocation = [touch locationInView:self.view];
    for (id sublayer in self.view.layer.sublayers) {
        BOOL touchInLayer = NO;
        if ([sublayer isKindOfClass:[CAShapeLayer class]]) {
            CAShapeLayer *shapeLayer = sublayer;
            if (CGPathContainsPoint(shapeLayer.path, 0, touchLocation, YES)) {
                // This touch is in this shape layer
                touchInLayer = YES;
            }
        } else {
            CALayer *layer = sublayer;
            if (CGRectContainsPoint(layer.frame, touchLocation)) {
                // Touch is in this rectangular layer
                touchInLayer = YES;
            }
        }
    }
}

}

于 2016-03-25T11:38:42.037 回答