swift - 如果 View 变得可动画,则有效地调整 CAShapeLayer 的大小

标签 swift uibutton cashapelayer

我有一个 UIButton,里面有一个 CAShapeLayer。这是子类代码的一部分:

private func addBeneathFill(){
    didAddedBeneathFill = true
    let halfBeneathFill = UIBezierPath()
    halfBeneathFill.move(to: CGPoint(x: 0, y: frame.height / 2))
    halfBeneathFill.addCurve(to: CGPoint(x: frame.width, y: frame.height / 2), controlPoint1: CGPoint(x: frame.width / 10, y: frame.height / 2 + frame.height / 10), controlPoint2: CGPoint(x: frame.width,      y: frame.height / 2 + frame.height / 10))
    halfBeneathFill.addLine(to: CGPoint(x: frame.width, y: frame.height))
    halfBeneathFill.addLine(to: CGPoint(x: 0, y: frame.height))
    halfBeneathFill.addLine(to: CGPoint(x: 0, y: frame.height / 2))
    let path = halfBeneathFill.cgPath
    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path
    let fillColor = halfBeneathFillColor.cgColor
    shapeLayer.fillColor = fillColor
    shapeLayer.opacity = 0.3
    layer.insertSublayer(shapeLayer, at: 2)
}

只要 UIButton 的大小不变,它就可以很好地工作。当它改变大小时,CAShapeLayer 只是停留在它原来的位置。当然,当 UIButton 的框架已更改时,我可以再次运行该方法,但在动画中它看起来很糟糕。

如何正确地设置 CAShapeLayer 的大小为 UIButton 的当前大小?

最佳答案

您需要在按钮框架更改时重新计算路径并设置动画。

private func animateShapeLayer() {
    let animation = CABasicAnimation(keyPath: "path")
    animation.fromValue = getBezierPath(forFrame: oldFrame)
    animation.toValue = getBezierPath(forFrame: newFrame)
    animation.duration = 1.0
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

    shapeLayer.add(animation, forKey: "path")
}

我已经测试过了,这里有一个 link到 Playground 要点并取得了成果:

enter image description here

关于swift - 如果 View 变得可动画,则有效地调整 CAShapeLayer 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48232999/

相关文章:

iphone - 将 UIImagePickerController 用于多个 uiimageview。 (使用多个UIButton)

ios - 在 iOS 中使用图层和部分渲染来提高速度的最佳方法是什么

ios - UIViewController 中的 UICollectionView

swift - Swift 中泛型的同一性比较

swift - 根据登录的用户从 firebase 加载数据

iOS:获取不在 drawRect 中的 CGMutablePath:并将其分配给 CAShapeLayer 的路径

ios - 动画边界变化时的 CAShapeLayer 路径动画

ios - 在 Swift 中使用 SecRandomCopyBytes

ios - 以编程方式设置 UIButton 的中心 - SWIFT

swift - 如何更改按钮的文字大小?