1

我不明白为什么 CAShapeLayer 不响应 hitTest

这个函数总是去 // 触摸在外面

如何检测 CAShapeLayer 上的触摸?

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{   

    currentPoint = [[touches anyObject] locationInView:self];

    for (CAShapeLayer *layer in self.layer.sublayers) {    

        如果(层 == shapeLayer){

            if([图层 hitTest:currentPoint])
            {
                // touche 在图层上
            }
            别的 {
                // 触摸在外面
            }

        }

    }       

}
4

2 回答 2

6

在敲了两天的头之后,我能够生成这个奇怪的代码,看起来它正在工作!

目标是测试 CAShapeLayer。CAShapeLayer 在屏幕上移动,所以形状不是固定的。对 CGPath currentPoint 进行命中测试并不简单。

随意添加任何输入...

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{   

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

    CGAffineTransform 转换 = CGAffineTransformMakeTranslation(-shapeLayer.position.x, -shapeLayer.position.y);

    if(CGPathContainsPoint(shapeLayer.path, &transf, p, NO)){    

       // 触摸在形状内部  
    }   

}
于 2011-02-13T21:48:47.153 回答
1

见下文 - 覆盖 CAShapeLayers hitTest() 方法

    // CAShapeLayer path coordinates are relative to the layer
    // so when hit testing to see if the mouse click is inside the path
    // convert the point to layer coordinates like so
    // This assumes the received coordinates are in the layers superlayer coordinates
    // Usually so if they come from a mouse click

    override func hitTest(_ p: CGPoint) -> CALayer? {
        
        let lp = self.convert(p, from: superlayer)
        
        let result = path?.contains(lp) ?? false
        
        return result ? self : nil
            
    }
于 2020-07-13T13:54:09.887 回答