代码之家  ›  专栏  ›  技术社区  ›  User

CALayer路径动画不工作

  •  1
  • User  · 技术社区  · 6 年前

    为什么此路径动画不起作用?

    let frame = CGRect(x: 20, y: 20, width: 10, height: 10)
    let frame2 = CGRect(x: 20, y: 20, width: 100, height: 100)
    
    let path = UIBezierPath(rect: frame)
    let path2 = UIBezierPath(rect: frame2)
    
    let animation = CABasicAnimation(keyPath: "path")
    animation.fromValue = path
    animation.toValue = path2
    animation.duration = 3
    animation.repeatCount = Float.greatestFiniteMagnitude
    
    let l = CAShapeLayer()
    l.path = path.cgPath
    l.fillColor = UIColor.black.cgColor
    self.view.layer.addSublayer(l)
    
    l.add(animation, forKey: "pathAnimation")
    

    完整操场:

    import UIKit
    import PlaygroundSupport
    
    class MyViewController : UIViewController {
    
        override func loadView() {
            let view = UIView()
            view.backgroundColor = .white
            self.view = view
    
            let frame = CGRect(x: 20, y: 20, width: 10, height: 10)
            let frame2 = CGRect(x: 20, y: 20, width: 100, height: 100)
    
            let path = UIBezierPath(rect: frame)
            let path2 = UIBezierPath(rect: frame2)
    
            let animation = CABasicAnimation(keyPath: "path")
            animation.fromValue = path
            animation.toValue = path2
            animation.duration = 3
            animation.repeatCount = Float.greatestFiniteMagnitude
    
            let l = CAShapeLayer()
            l.path = path.cgPath
            l.fillColor = UIColor.black.cgColor
            self.view.layer.addSublayer(l)
    
            l.add(animation, forKey: "pathAnimation")
        }
    }
    
    PlaygroundPage.current.liveView = MyViewController()
    
    1 回复  |  直到 6 年前
        1
  •  6
  •   ukim    6 年前

    你应该在动画中使用cgPath

        animation.fromValue = path.cgPath
        animation.toValue = path2.cgPath