What is pulse animation in iOS?
As its name describes, ‘Pulse animation‘ is an animation the comes and go just like a wave of water. The animation start gradually and fades away as its reach its end time. For more visualized example of pulse animation in iOS please, look at the image below.
In this tutorial, we will learn how to create pulse animation using swift language in iOS (will create exactly same screen as shown the exemplary image above). So let’s start the tutorial
Steps to create pulse animation in swift :
Step 1: Create a new Xcode project, we are using “single view application” template for the tutorial.
Step 2: Open ViewController.swift file, create an IBOutlet for the imageView (required as pulse animation origin )
Step 3: Open Main.storyboard, drag a UIImageView object to Viewcontroller’s view. Connect
IBOutlet created in step 2 to the UIImageView.
Step 4: Give UIIMageView constraint’s, below are the constraints applied to UIImageView
- Horizontally in container
- Vertically in container
- Width = 50
- Height = 50
Step 5: Assign “avatar” image to UIImageView. You can grab a copy of the avatar assets from here.
Step 6: As we are all set up with our design part let’s dive into the most interesting part of this tutorial, i.e. creating pulse animation in iOS using swift language.
Step 7: Since, we are creating a circular pulse animation so for this we also need our object which acts as a pulse origin, to be circular too, in our case its avatar imageView. So make UIImageView circular.
Step 8: Its time to create pulse layer, so we will create a new function and named it “createPulse“. Below is the code that creates pulse
In above code, we created a circular path using UIBezierPath, setting following parameters as
1) arc center of the circular path to zero initially though we will set center of our circular pat later on.
2) Radius of the circular path will equals to the width of your pulse animation divides by 2 i.e how long you want the pulse to go and then fades away.
3) Start angle of the circular path will be zero so that it starts from its initials point.
4) End angle will be 2 *.pi
5) Direction of circular path will be clockwise, it tells whether layer draws itself clock wise or anticlockwise
As we are done with circular path , we need to create a layer using CAShapeLayer class that will act as our pulse. Assign the properties to layer object as shown in the code above and finally add the layer to our avatar UIImageView layer. This is required as our avatar UIImageView acts as origin of pulse. Lastly, add layer to the array too.
Step 9: Call the “createPulse” function inside viewDidLoad function.
Animate Pulse around avatar UIIMageView:
The above code is self explanatory, if you have any concerns or doubts then please feel free to ask then in comments.
In order to start animation we need to call the “animatePulsatingLayerAt” function as shown below