如果视图变得可动画,则高效调整CAShapeLayer的大小

时间:2018-01-12 19:39:19

标签: 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的当前大小?

1 个答案:

答案 0 :(得分: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到游乐场的要点并取得了成果:

enter image description here