ios - CAShapeLayer 在动画 Swift 期间检测触摸

标签 ios swift core-animation cashapelayer cabasicanimation

我可以像这样检测到 CAShapeLayer 的触摸(touchesEnded):

let touchLocation : CGPoint = (touch as! UITouch).locationInView(self.view)

for shape in shapes{
    if CGPathContainsPoint(shape.path, nil, touchLocation, false){
        print("Layer touch")
    }
}

我可以像这样为 CAShapeLayer 的路径设置动画:

let newShapePath = UIBezierPath(arcCenter: toPoint, radius: 20, startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true).CGPath

// animate the `path`
let animation = CABasicAnimation(keyPath: "path")
animation.toValue = newShapePath
animation.duration = CFTimeInterval(duration)

animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
animation.fillMode = kCAFillModeBoth
animation.removedOnCompletion = false

shape.addAnimation(animation, forKey: animation.keyPath)

但是当动画发生时,在 CAShapeLayer 上没有检测到触摸。是否可以在为路径设置动画时检测到 CAShapeLayer 上的触摸?

最佳答案

您可以访问图层的 presentationLayer为此。这将为您提供动画时给定层的“飞行中”值的粗略近似值。例如:

for shape in shapes {

    // gets the layer's presentation layer if it exists – else fallback on the model layer
    let presentationLayer = shape.presentationLayer() as? CAShapeLayer ?? shape

    if CGPathContainsPoint(presentationLayer.path, nil, touchLocation, false){
        print("Layer touch")
    }
}

此外,作为旁注,如果您不使用动画委托(delegate),则使用 removedOnCompletion = false 通常被认为是不好的做法。不要让动画挥之不去,您应该只更新图层的模型值以表示其新状态。您可以通过 CATransaction 来确保不会生成隐式动画。例如:

let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = shape.path
animation.toValue = newShapePath
animation.duration = CFTimeInterval(duration)

animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)

shape.addAnimation(animation, forKey: animation.keyPath)

// update the layer's model values
CATransaction.begin()
CATransaction.setDisableActions(true)
shape.path = newShapePath
CATransaction.commit()

关于ios - CAShapeLayer 在动画 Swift 期间检测触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102573/

相关文章:

ios - 如何应用复杂的 CALayer 变换更改?

ios - 多次调用 removeFromSuperView 会导致崩溃/错误吗?

ios - 快速创建 2 个可扩展行下拉菜单?

ios - 无法将 UIButton Outlet 添加到 UIView

ios - Type Any 没有下标成员 json Swift 3

swift - 当类型是关联类型时,无法将类型的值转换为预期的参数类型

cocoa - 可编辑的 CATextLayer?

swift - CGAffineTransformMakeRotation 和 CGAffineTransformRotate 的区别

iphone - 删除了/Developer/Platforms/iPhoneOS.platform/DeviceSupport 文件夹,现在我无法在我的设备上进行测试

ios - UIToolbar 中工具栏项之间的分隔符