我正在开发一个 iOS 应用程序,我需要在 UIView 上创建涟漪效果。我可以创建涟漪效果,但无法自定义。这就是我想要实现的目标:
这是我当前的输出
我想要实现的是连续创建 4-5 个涟漪,然后在一些延迟之后再产生 4-5 个涟漪并无限重复该过程。但目前我只能产生 1 个波纹(它会无限传播)。
这是我的代码:
func addRipple(rView: UIView) {
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: rView.bounds.size.width, height: rView.bounds.size.height))
let shapePosition = CGPoint(x: rView.bounds.size.width / 2.0, y: rView.bounds.size.height / 2.0)
let rippleShape = CAShapeLayer()
rippleShape.bounds = CGRect(x: 0, y: 0, width: rView.bounds.size.width, height: rView.bounds.size.height)
rippleShape.path = path.cgPath
rippleShape.fillColor = UIColor.clear.cgColor
rippleShape.strokeColor = UIColor.systemBlue.cgColor
rippleShape.lineWidth = 1
rippleShape.position = shapePosition
rippleShape.opacity = 0
rView.layer.addSublayer(rippleShape)
let scaleAnim = CABasicAnimation(keyPath: "transform.scale")
scaleAnim.fromValue = NSValue(caTransform3D: CATransform3DIdentity)
scaleAnim.toValue = NSValue(caTransform3D: CATransform3DMakeScale(2, 2, 1))
let opacityAnim = CABasicAnimation(keyPath: "opacity")
opacityAnim.fromValue = 1
opacityAnim.toValue = nil
let animation = CAAnimationGroup()
animation.animations = [scaleAnim, opacityAnim]
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
animation.duration = 1
animation.repeatCount = Float.infinity
animation.isRemovedOnCompletion = false
rippleShape.add(animation, forKey: "rippleEffect")
}
这就是我调用 addRipple 方法的方式
@IBOutlet weak var sView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
sView.layer.cornerRadius = sView.frame.size.width / 2
sView.layer.borderWidth = 2
sView.layer.borderColor = UIColor.systemBlue.cgColor
addRipple(to: sView)
}
我觉得我很接近,但我无法弄清楚。
提前致谢。
你可以使用这个 Pod 或 UIView Extension
信用:https://github.com/janlionly/UIView-Ripple/blob/master/Source/UIView%2BRipple.swift
如果我没理解错的话,你希望这些涟漪中的多个同时出现在屏幕上。在这种情况下,如果您创建多个圆形子图层并使用不同的
timeOffset
为它们中的每一个设置动画,将会更方便。
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: rView.bounds.size.width, height: rView.bounds.size.height))
let shapePosition = CGPoint(x: rView.bounds.size.width / 2.0, y: rView.bounds.size.height / 2.0)
for i in 0..<4 {
let rippleShape = CAShapeLayer()
// set up rippleShape as usual here...
rView.layer.addSublayer(rippleShape)
// set these up as usual too...
let scaleAnim = ...
let opacityAnim = ...
let animation = CAAnimationGroup()
animation.animations = [scaleAnim, opacityAnim]
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
animation.repeatCount = Float.infinity
animation.duration = 2
animation.isRemovedOnCompletion = false
// this is the important section
// let timeInBetweenRipples = 0.2
animation.timeOffset = timeInBetweenRipples * Double(i)
animation.speed = 0.5
// You can tweak speed, timeInBetweenRipples, and duration as you see fit
// don't forget to give each animation a different key
rippleShape.add(animation, forKey: "rippleEffect\(i)")
}
动画的一帧是这样的: