使用以下代码,我可以从左到右为CALayer设置动画
let imageLayer = CALayer()
imageLayer.frame = CGRect(x: 0, y: 500, width: 100, height: 70)
imageLayer.contents = UIImage(named: "first_image")?.cgImage
let animation = CABasicAnimation()
animation.keyPath = "position.x"
animation.fromValue = 100
animation.toValue = 300
animation.duration = 3
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = true
animation.repeatCount = 2
imageLayer.add(animation, forKey: "basic")
self.view.layer.addSublayer(imageLayer)
我想要做的是,
周期:1 - “first_image”将从左向右移动
并在
周期:2 - “second_image”(这是另一张图片)将从左侧移动 像上一个周期一样正确。
这里周期:1 + 周期:2 实际上是一个动画,我希望这个动画多次发生。怎么做到这一点? 任何帮助将不胜感激。
答案 0 :(得分:0)
因为你需要从左到右&反之亦然动画,您也可以使用UIView.anima..
进行动画制作。
let testViewTowardsLeft = UIView(frame: CGRect(x: 0, y: 150, width: 50, height: 50))
testViewTowardsLeft.backgroundColor = .red
view.addSubview(testViewTowardsLeft)
UIView.animate(withDuration: 1, delay: 0, options: .repeat, animations: {Bool in
testViewTowardsLeft.frame = CGRect(x: 100, y: 150, width: 50, height: 50)
}, completion: nil)
let testViewTowardsRight = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50))
testViewTowardsRight.backgroundColor = .red
view.addSubview(testViewTowardsRight)
UIView.animate(withDuration: 1, delay: 0, options: .repeat, animations: {Bool in
testViewTowardsRight.frame = CGRect(x: 0, y: 100, width: 50, height: 50)
}, completion: nil)