Im使用CABasicAnimation制作像脉冲帧一样的动画视图
有代码
extension UIView {
/// animate the border width
func animateBorderWidth(toValue: CGFloat, duration: Double) -> CABasicAnimation {
let widthAnimation = CABasicAnimation(keyPath: "borderWidth")
widthAnimation.fromValue = 0.9
widthAnimation.toValue = 0.0
widthAnimation.duration = 15
widthAnimation.timingFunction = CAMediaTimingFunction(name: .easeOut)
return widthAnimation
}
/// animate the scale
func animateScale(toValue: CGFloat, duration: Double) -> CABasicAnimation {
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 1.0
scaleAnimation.toValue = 12
scaleAnimation.duration = 55
scaleAnimation.repeatCount = .infinity
scaleAnimation.isRemovedOnCompletion = false
scaleAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
return scaleAnimation
}
func pulsate(animationDuration: CGFloat) {
var animationGroup: CAAnimationGroup!
let newLayer = CALayer()
animationGroup = CAAnimationGroup()
animationGroup.duration = CFTimeInterval(animationDuration)
animationGroup.repeatCount = Float.infinity
newLayer.bounds = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
newLayer.cornerRadius = self.frame.width/2
newLayer.position = CGPoint(x: self.frame.width/2, y: self.frame.height/2)
newLayer.cornerRadius = self.frame.width/2
newLayer.borderColor = #colorLiteral(red: 0.7215686275, green: 0.5137254902, blue: 0.7647058824, alpha: 0.7).cgColor
animationGroup.timingFunction = CAMediaTimingFunction(name: .easeOut)
animationGroup.animations = [animateScale(toValue: 7.5, duration: 2.0),
animateBorderWidth(toValue: 0.6, duration: Double(animationDuration))]
animationGroup.duration = 14
newLayer.add(animationGroup, forKey: "pulse")
self.layer.cornerRadius = self.frame.width/2
self.layer.insertSublayer(newLayer, at: 0)
}
func removeAnimation() {
self.layer.sublayers?.forEach { $0.removeAnimation(forKey: "pulse") }
}}

并将此动画添加到UIViewCOntroller中查看
func startPul() {
self.backPulseView.pulsate(animationDuration: 2.0)
}但如果我按下按钮,我想停止动画并隐藏我正在尝试
func stopPul() {
self.backPulseView.removeAnimation()
}但动画仍在运行且不会被删除
如何删除动画,然后才能再次调用?
停止我从点击按钮调用的动画
@IBAction func stopBtn(_ sender: UIButton) {
stopPul()
}发布于 2021-10-16 11:11:01
要移除遍历sublayers的动画并移除该"pulse“关键点的动画,请执行以下操作:
self.layer.sublayers?.forEach {
$0.speed = 0
$0.removeAllAnimations()
$0.removeFromSuperlayer()
}
}https://stackoverflow.com/questions/69594479
复制相似问题