By Pranjal Satija, author of this article. Proofread: Cee; Finalized: CMB

Welcome! This article will teach you about one of the key technologies in iOS: Layers. You probably already know about views in iOS, but you probably didn’t know that behind each individual view is something called a layer. Layers are the contents of the Core Animation framework.

You might be wondering, “I’ve never used a layer, so maybe it’s not that important?” Whether you know it or not, your application uses layers a lot. No matter what view it is, a view on iOS will contain a layer. Because of layers, iOS can easily detect the bitmap information of the view in your app and then feed it to the device’s GPU. See the image below (from Apple) to clearly show where Core Animation fits in the iOS hierarchy.

Why use layers?

On devices like smartphones, users expect everything they do to be fast. Maintaining a consistent frame rate is key so that the user feels “silky and smooth.” In iOS, the frame rate is 60 frames per second. To keep the system running at this rate, a very basic but powerful graphical layer was created that ran directly on the GPU: OpenGL.

OpenGL provides most of the low-level (and fastest) access to the iOS device’s graphics hardware. However, you need to make a tradeoff: OpenGL is so close to the bottom that it requires a lot of code for even the simplest tasks.

To alleviate this problem, Apple created Core Graphics, which provided more advanced methods and thus less code. Core Graphics was originally intended to be used for low-level functions. To make Core Graphics easier to use, Apple created Core Animation. It provides the CALayer class and allows some basic low-level image manipulation.

UIKit, which provides top-level image access in iOS, was born when Apple decided that many of the advanced features in Core Animation weren’t always needed in regular applications. The advantage of this design is that in your application, you can choose the level of image access you need and apply it, allowing you to pick and choose precisely the level of functionality you need without having to write useless code. The downside is that the higher-level graphics apis provide less functionality. This story is told to illustrate: Because of the CALayer, iOS can see the view hierarchy in your app, quickly generate bitmap information about the hierarchy, and then pass it to Core Graphics, and eventually to OpenGL, so that the image is processed by the device’s GPU and presented on the screen. Although you don’t need to use CALayer directly in most cases, the lower-level API provides users with some more flexible customizations, which we’ll discuss in this article.

Visit CALayer

Enough has been said about why layers exist. Let’s do it! As I mentioned above, each view has a layer to support it, which can be accessed through the LAYER property of UIView. Suppose you have a myView object, you can access its layer like this:


myView.layer

Okay, so now we have access to the layer, what can we do with it? You’ll be surprised at how much you can do. I’ll show you some of these tricks and effects in the rest of this tutorial.

The sample project

First, open the template project and let’s get started! The best way to learn is to do it, so we’re going to add custom effects to the views in this application. Open up the project and you’ll find that it’s pretty simple. It is a blank white view with a square black subview in the center. Let’s spruce it up a bit. Open the sample project, jump to ViewController.swift, and get started.

Create a rounded corners

You can use the cornerRadius property of the CALayer to set the corner of the layer edge. Let’s try it. Add the following code to viewDidLoad() :


box.layer.cornerRadius = 5

As expected, this will add a rounded corner with radius 5 to the box layer. It looks like this:

Not too bad, right? For large corners, increase the radius of the rounded corners, and for small corners, decrease the radius of the rounded corners. By default, all layers have a rounded radius of 0.

Add a shadow effect

Shadows help us create a sense of depth in our applications and are very useful in interface design. Using the shadow effect, you can “float” the view on the screen. Let’s take a look at how to create a shadow effect using a CALayer. Add the following code to the viewDidLoad method of the ViewController:

box.layer.shadowOffset = CGSizeMake(5, ShadowRadius = 5 box-layer. shadowColor = UIColor(red: 44.0/255.0, green: 62.0/255.0, blue: 80.0/255.0, alpha: 1.0).cgcolor

Line 1: this line sets the offset of the layer shadow to (5,5). Take a parameter of type CGSize in layer.shadowOffset. Passing (5, 5) to layer.shadowOffset means that the layer’s shadow will appear on the five points to the right of box.layer and the five points to the bottom.

Second line: This line sets the opacity of the layer shadow to 0.7. This means that the shadow should be 70% opaque.

Line 3: This line sets the layer shadow range to 5. The shadow range represents the blur range of the shadow created by box.layer. A higher range value means that shadows are more diffuse, but less visible. The lower range values make the shadows more visible and focused. A shadow range of 0 will result in no blur at all. In other words, it keeps the shadow exactly the same size and shape as the layer.

Line 4: This line sets the color of the layer’s shadow to midnight blue. Note that this attribute is of type CGColor, not a UIColor. Converting between the two types is very easy. You just write myUIColor.CGColor.


Let’s see the effect!

Application of border

CALayer also allows us to easily use borders. Let’s add a border to the box.


box.layer.borderColor = UIColor.blueColor().CGColor
box.layer.borderWidth = 3

Line 1: This line sets the border color to midnight blue. This will make any border on the box appear blue.

Second line: This line sets the width of the border to 3. This means that the border drawn around the box will be 3 points thick.

Let’s see what the box looks like with the added borders.

According to the image

You can also assign an image to a layer to show the image on the layer. There is a lovely picture of a tree in the sample project, thanks to the website. Let’s show this image with layers. Add the following code to viewDidLoad:


box.layer.contents = UIImage(named: "tree.jpg")?.CGImage
box.layer.contentsGravity = kCAGravityResize
box.layer.masksToBounds = true

Line 1: This line creates a UIImage object with the file name tree.jpg and passes it to the contents property of the layer.

Second line: This line sets the content center of the layer to resize, which means that everything in the layer will be resized to perfectly fit the size of the layer.

Line 3: We set masksToBounds to true so that any sublayers in the layer that extend beyond the boundary will be clipped at the boundary. If you don’t know what this means, you can set the value to false and see the effect.

Here’s the effect.

Background color and opacity

We’ve already discussed how to add special effects to a CALayer that can’t be done in UIKit, but we should also discuss how to modify most of the properties that UIKit exposes to UIViews through a CALayer. For example, you can change the background color and opacity of the view:

Box. Layer. The backgroundColor = UIColor. BlueColor (). The CGColor box. The layer. The opacity = 0.5

The performance of the CALayer

Adding a lot of custom effects to layers can have a performance impact. Now, we’ll discuss two properties of the CALayer that can help you dramatically improve the performance of your application.

First, let’s talk about drawsAsynchronously. This property is used on the CALayer to specify whether the actions that the CPU must perform while drawing the layer need to be performed in the background thread. If this property is set to true, the layer looks the same as usual, but the CPU calculations needed to draw it are performed in a background thread. Set this to true if your application has a view that needs to be redrawn heavily (such as a map view or table view).

The other property is shouldRasterize. This is another property on the CALayer. It specifies whether the layer should be rasterized. When this property is set to true, the layer is drawn only once. Each time a layer is animated, the layer is not redrawn, but reuses the bitmap information from the first time it was drawn. Set this property to true if your application has a view that does not need to be redrawn frequently. Note that when shouldRasterize is set, the layer’s appearance may be different on Retina devices. This is because layers have a so-called rasterization ratio, which is used when a layer is rasterized. To prevent this from happening, set the rasterizationScale of the layer to uiscreen.mainScreen ().scale so that the rasterizationScale of the layer is consistent with the scale of the screen drawing.

Note that 99% of the time you don’t need to set these properties yourself. Setting them manually can result in poor performance. If you are sure that the drawing of a view or layer is affecting the performance of your application, you can only set one of these two properties yourself.

conclusion

Now you know what a CALayer is! Knowing some low-level graphics can help you create some cool effects in your application. I hope you enjoyed this beginner’s guide.

For reference, you can download the sample project on GitHub. If you have any questions or feedback, please leave me a comment below.

This article was translated by the SwiftGG translation group, with permission from the author. The latest article can be found at http://swift.gg.