【问题标题】:CAShapeLayer hitTest touchCAShapeLayer hitTest touch
【发布时间】:2011-02-12 21:56:08
【问题描述】:

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

这个函数总是去 // touches is outside

如何检测 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 在图层上 } 别的 { // 触摸在外面 } } } }

【问题讨论】:

    标签: iphone uikit core-graphics quartz-graphics cashapelayer


    【解决方案1】:

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

    我们的目标是测试 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)){ // 触摸在形状内部 } }

    【讨论】:

      【解决方案2】:

      见下文 - 覆盖 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
                  
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-15
        • 2020-10-05
        • 1970-01-01
        相关资源
        最近更新 更多