Software Development Blog


Quickstart with CALayer and CABasicAnimation

What is CALayer?

CALayer is an object from the Core Animation framework. Each UIView backed by CALayer class, and you can easily find it in view.layer property. This class helps us to modify views and animate them. Basically, you animate a layer of view, but UIView size, position, etc depend on the layer property. So, in the creation of the layout part of an application, you need to know about basic CALayer objects and how to control them and their animation.

How to change the basic properties of UIView?

The most needed properties of view.layer property you can see below. It will answer most of the questions about UIView customization.

  • How to change cornerRadius of UIView
  • How to add shadow to UIView
  • How to add a border to UIView

Could UIView has more than one layer?

UIView has only one layer in view.layer property. But, you can easily add sublayer to this property like add subviews to view.

All these methods are very similar to methods for work with UIViews.

We can easily add sublayers to another layer like in code bellow:

How to animate properties of CALayer? CABasicAnimation

CALayer can have multiple animations. I will show you how to animate the layer's properties. Let's create an object of CABasicAnimation.

So, the main part of all animation is fromValue and toValue properties. In all animations, you need to set the start point of the position and end point of the animated layer. fromValue and toValue properties must be in Types like property that you are trying to animate. So in animation for background color, fromValue and toValue will be a CGColor Type. And when the animation is created, you can easily add it to the layer like above.

About masksToBounds: Bool property of CALayer

masksToBounds - a Boolean indicating whether sublayers are clipped to the layer’s bounds.

The red layer has masksToBounds = true, the yellow - masksToBounds = false.

What the difference between CALayer animation and UIView.animate way?

Animations of UIViews happens on the main thread and it means it is using CPU power. Layers are drawn directly on the GPU. It happens on a separate thread without burdening the CPU. So CALayer animations are more efficient, but we can't animate layout constraints of view with CALayer.

Ok, but how to 100% synchronize them?

CATransaction is a singleton class that can help to work with animations. All code between CATransaction.begin() and CATransaction.commit() will be executed at same time. CATransaction.setCompletionBlock will help you to handle the end of the animation. So it is easy to synchronize multiple animations.

How to use multiple animations and sublayers!


Here you can find all properties that you can animate in this way.

I hope you enjoy this tutorial about CALayer and basic work with sublayers and animations!

Recent Posts

What are UUID identifiers in Swift?


How to use Comparable protocol