Swift:Add Ripple effect to a view

anoop m
2 min readApr 16, 2018

--

When you need user attention to any part of your App, what would be the best way to grab user’s attention?

Animations is what I could think of….there are multiple options like

  1. Shake the view
  2. Scale Animation
  3. Opacity Animations
  4. Custom Animations (like Ripple)

In this write up I am going to talk about adding a Ripple animation around a view.

I am going to create a function which takes up a reference view which is going to be a UIView or its subclasses and I am going to use Coregraphics and CoreAnimation

Lets create a function name addRippleEffect

func addRippleEffect(to referenceView: UIView) {
}
  1. Create a circular path around the view
let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: referenceView.bounds.size.width, height: referenceView.bounds.size.height))

2. Create a ShapeLayer and position it and provide colors and the oval path that we created

/*! Position where the shape layer should be */let shapePosition = CGPoint(x: referenceView.bounds.size.width / 2.0, y: referenceView.bounds.size.height / 2.0)let rippleShape = CAShapeLayer()rippleShape.bounds = CGRect(x: 0, y: 0, width: referenceView.bounds.size.width, height: referenceView.bounds.size.height)rippleShape.path = path.cgPathrippleShape.fillColor = UIColor.clear.cgColorrippleShape.strokeColor = UIColor.yellow.cgColorrippleShape.lineWidth = 4rippleShape.position = shapePositionrippleShape.opacity = 0

3. Add the ripple layer as the sublayer of the reference view

referenceView.layer.addSublayer(rippleShape)

4. Create scale animation of the ripples

let scaleAnim = CABasicAnimation(keyPath: "transform.scale")scaleAnim.fromValue = NSValue(caTransform3D: CATransform3DIdentity)scaleAnim.toValue = NSValue(caTransform3D: CATransform3DMakeScale(2, 2, 1))

5. Create animation for opacity of the ripples

let opacityAnim = CABasicAnimation(keyPath: "opacity")opacityAnim.fromValue = 1opacityAnim.toValue = nil

6. Group the opacity and scale animations

let animation = CAAnimationGroup()animation.animations = [scaleAnim, opacityAnim]animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)animation.duration = CFTimeInterval(0.7)animation.repeatCount = 25animation.isRemovedOnCompletion = true

7. Add animations to the shape

rippleShape.add(animation, forKey: "rippleEffect")

8 . Call it

func animateImage() {addRippleEffect(to: imageView)}

Finished code can be found here

ObjC:RippleEffectObjC

Swift:RippleEffectSwift

--

--

Responses (1)