边界层动画无法从中心缩放

时间:2018-12-19 09:42:25

标签: ios animation core-animation calayer

我正在为一个奇怪的问题苦苦挣扎,例如当我将比例转换添加到任何图层时,它并没有从中心进行动画处理。它是起源的。

func addSquareBorderLayer() {

    borderLayer = CAShapeLayer()
    let rect = CGRect(x: spotlight!.frame.origin.x, y: spotlight!.frame.origin.y, width: spotlight!.frame.width, height: spotlight!.frame.height)
    borderLayer?.path = UIBezierPath(roundedRect: rect, cornerRadius: spotlight!.cornerRadius).cgPath
    borderLayer?.strokeColor = UIColor(red: 91/255, green: 186/255, blue: 162/255, alpha: 1).cgColor //ColorRGB(91, 186, 162)
    borderLayer?.lineWidth = spotlight!.cornerRadius
    borderLayer?.fillColor = UIColor.clear.cgColor
    layer.addSublayer(borderLayer!)

    animatePulsatingLayer(pulsatingLayer: layer)
}

private func animatePulsatingLayer(pulsatingLayer : CALayer) {
    let animation = CABasicAnimation(keyPath: "transform.scale")
    animation.duration       = 0.5
    animation.repeatCount    = .greatestFiniteMagnitude
    animation.autoreverses   = true
    animation.fromValue      = 1
    animation.toValue        = 1.05
    pulsatingLayer.add(animation, forKey: "pulsing")
}

有人可以帮忙吗?

参考正在发生的事情:https://www.dropbox.com/s/0hqdrrv310du7vz/mo.mov?dl=0

1 个答案:

答案 0 :(得分:0)

有点棘手。您需要将图层的frame设置为当前为rect设置的path。并将路径origin设置为零,以便在与框的原点相同的位置绘制圆(或任何形状)。这将允许在anchorPoint(0.5,0.5)处应用动画。

这是完整的示例,

var borderLayer: CAShapeLayer!

func addSquareBorderLayer() {

    let size: CGFloat = 100

    borderLayer = CAShapeLayer()
    let rect = CGRect(origin: .zero, size: CGSize(width: size, height: size))
    borderLayer?.path = UIBezierPath(roundedRect: rect, cornerRadius: 50).cgPath
    borderLayer?.strokeColor = UIColor(red: 91/255, green: 186/255, blue: 162/255, alpha: 1).cgColor
    borderLayer?.lineWidth = 20
    borderLayer?.fillColor = UIColor.clear.cgColor
    borderLayer?.frame = CGRect(origin: CGPoint(x: 100, y: 200), size: rect.size)
    self.view.layer.addSublayer(borderLayer!)

    animatePulsatingLayer(pulsatingLayer: borderLayer!)
}

private func animatePulsatingLayer(pulsatingLayer : CALayer) {
    let animation = CABasicAnimation(keyPath: "transform.scale")
    animation.duration       = 0.3
    animation.repeatCount    = .greatestFiniteMagnitude
    animation.autoreverses   = true
    animation.fromValue      = 1
    animation.toValue        = 1.2
    pulsatingLayer.add(animation, forKey: "pulsing")
}

结果

enter image description here