【问题标题】:Efficient resize the CAShapeLayer if the view grows animatable如果视图变得可动画,则有效地调整 CAShapeLayer 的大小
【发布时间】:2023-07-13 01:31:01
【问题描述】:

我有一个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 的当前大小?

【问题讨论】:

    标签: swift uibutton cashapelayer


    【解决方案1】:

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

    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 到操场的要点并取得了结果:

    【讨论】:

      最近更新 更多