【问题标题】:Border Layer animation not Scaling from Center边框层动画不从中心缩放
【发布时间】:2019-05-19 18:40:53
【问题描述】:

我正在努力解决一个奇怪的问题,例如当我向任何图层添加比例变换时,它不会从中心进行动画处理。它是从原点开始的。

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

【问题讨论】:

标签: ios animation core-animation calayer


【解决方案1】:

这有点棘手。您需要将图层的frame 设置为您当前为path 设置的rect。并将路径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")
}

结果

【讨论】:

  • 你能说它适用于方形或矩形吗?
  • 是的,动画适用于任何类型的形状,这意味着它将从中心对其进行动画处理。
猜你喜欢
  • 2021-09-14
  • 2019-12-28
  • 2021-04-23
  • 1970-01-01
  • 2023-03-08
  • 2018-09-18
  • 2011-11-14
  • 2015-11-22
  • 2017-07-26
相关资源
最近更新 更多