The layer tree

Core Animation actually evolved from Layer Kit, a name not associated with Animation, so Animation is just the tip of the iceberg.

Core Animation is a composite engine whose job is to combine different visual content on the screen as quickly as possible. This content is decomposed into separate layers and stored in a system called layer tree. So this tree forms the basis of UIKit and everything you see on screen in iOS apps.

Layers and Views

Views can be nested within a hierarchy, and a view can manage the location of all its child views.

In iOS, all views are derived from a base class called UIView, which can handle touch events, can support Core Graphic-based drawing, can do affine transformations (such as rotation or scaling), or simple animations like sliding or gradients.

CALayer

The biggest difference with UIView is that CALayer doesn’t handle user interaction. CALayer doesn’t know the exact response chain (the mechanism iOS uses to send touch events through the view hierarchy), so it can’t respond to events.

Parallel hierarchy

Each UIView has the backing layer property of a CALayer instance.

In fact, these layers are really used for displaying and animating on the screen. UIView is just an encapsulation of it, providing some specific functions of iOS like handling touch, as well as high-level interfaces to the underlying methods of Core Animation.

IOS provides two parallel hierarchies based on UIView and CALayer because of the separation of responsibilities, which also avoids a lot of repetitive code.

In fact, instead of two levels, there are four, and in addition to the view level and layer tree, there are also render trees and render trees, which we’ll talk about later.

Layer power

There are a few CALayer functions that UIView does not expose:

  • Shadows, rounded corners, colored borders

  • 3 d transform

  • Non-rectangular range

  • Transparent mask

  • Multistage nonlinear animation

Using the layer

The advantage of using layer-associated views instead of CALayer is that you can use all of CALayer’s low-level features while also using UIView’s advanced apis (such as automatic typography, layout, and event handling).

However, you may want to use a CALayer rather than a UIView when the following conditions are met

  • Develop cross-platform applications that can also run on Mac OS

  • Use multiple subclasses of CALayer, and don’t want to create additional UIViews to wrap all of them

  • Doing things that are particularly performance critical, such as doing negligible operations on UIView, can make a significant difference (however, you may want to use OpenGL drawing directly)

    Metal was introduced in 2014 as a general purpose API for GPU-based computation. In 2018, Apple deprecated OpenGL in iOS 12 for both iOS and macOS.

conclusion

This chapter explains the layer tree structure and shows how a parallel CALayer hierarchy is formed by UIView hierarchy in iOS.