代码之家  ›  专栏  ›  技术社区  ›  Sohil R. Memon

边界层动画不从中心缩放

  •  1
  • Sohil R. Memon  · 技术社区  · 6 年前

    我正在努力解决这个奇怪的问题,比如当我向任何层添加缩放变换时,它都不是从中心开始动画的。它是从起源开始的。

    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 回复  |  直到 6 年前
        1
  •  0
  •   Kamran    6 年前

    有点棘手。你需要设置 frame 对于作为 rect 您当前正在为 path origin 使圆(或任何形状)绘制在与帧原点相同的位置。这将允许动画应用于 anchorPoint

    下面是完整的例子,

    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