skip to content

Core Animation

Core Animation runs the CALayer tree under every UIKit view: implicit actions, keyframe animations and 3D transforms. Interviewers probe model versus presentation layers and the render server.

on this pageshow

explore

questions

6

In Core Animation, what is a UIView's backing CALayer, and why does setting cornerRadius alone not clip an image view's picture to a circle?

level: juniorimportance: must knowfreq 70%

answer

  1. every view owns one layer
  2. layerClass picks its type
  3. background and border, not contents
  4. an implicit mask matching the bounds
  5. that mask also cuts the shadow

basics

~20 s

Every UIView renders through a backing CALayer created from its layerClass, with the view as the layer's delegate. A layer's cornerRadius rounds only its background and border; the image in its contents is clipped once masksToBounds is true.

solid answer

~40 s

A `UIView` does not composite pixels itself: it owns a `CALayer`, exposed as the read-only `view.layer`, which UIKit creates once, early in the view's life, from the class property `layerClass`, and the view is that layer's delegate. Overriding `layerClass` to return `CAGradientLayer.self` or `CAShapeLayer.self` makes that type the view's own layer. On the layer, `cornerRadius` rounds the background color and the border; Apple's documentation says it does not apply to the image in `contents` by default. Setting `masksToBounds` to `true` (the view-level switch is `clipsToBounds`) adds an implicit mask that matches the bounds, corner radius included, so the image and any sublayers are clipped to the curve. The price is that the same mask also cuts off a shadow drawn outside the bounds.

code

swift · 26 lines
swift
import UIKit

// A view whose backing layer is a CAGradientLayer instead of a plain CALayer.
final class TechniqueCardView: UIView {
    override class var layerClass: AnyClass { CAGradientLayer.self }

    private var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }

    override init(frame: CGRect) {
        super.init(frame: frame)
        gradientLayer.colors = [UIColor.systemTeal.cgColor, UIColor.systemBlue.cgColor]
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}

@MainActor
func makeCoachAvatar() -> UIImageView {
    let avatar = UIImageView(image: UIImage(systemName: "wind"))
    avatar.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
    avatar.backgroundColor = .systemGray5
    avatar.layer.cornerRadius = 40          // rounds the background and border only
    avatar.layer.cornerCurve = .continuous
    avatar.layer.masksToBounds = true       // now the image is clipped to the circle too
    return avatar
}

go deeper

for a junior

Recall that each view has one backing CALayer, that cornerRadius rounds background and border, and that masksToBounds or clipsToBounds is what clips the picture.

for a middle

Explain layerClass as the way to make a gradient or shape layer the view's own, and why that beats a sublayer you must resize by hand.

for a senior

Show you know the bounds mask also removes shadows, and describe the outer-shadow, inner-clip structure with a shared radius and an explicit shadowPath.

for a principal

Frame a team convention for rounded, shadowed components: one shared component that splits shadow and clipping, so every screen gets the shape right and pays the rendering cost once.

## Every view is backed by a layer In UIKit, a **`UIView`** handles layout, touches and accessibility, but what reaches the screen is its **`CALayer`**, Core Animation's object for visual content and geometry. Each view has exactly one backing layer, read through `view.layer`, a property that is never `nil` and cannot be assigned. The view becomes the layer's **delegate**, which is how it supplies drawing and decides how the layer reacts to property changes. Three consequences follow: - Visual attributes the view does not expose directly (`borderWidth`, `borderColor`, `shadowOpacity`, `shadowPath`) are set on `view.layer`. - Apple's documentation warns never to change the backing layer's delegate and never to make a view the delegate of another layer. - Layers can also live without a view: a `CAShapeLayer` added with `addSublayer(_:)` draws, but it takes no touches and has no Auto Layout. Because these are plain layer properties, a change such as `view.layer.borderWidth = 2` needs no redraw call: Core Animation composites the layer with its new border on a following frame, without running the view's `draw(_:)`. ## Choosing the layer's class with layerClass The class property **`layerClass`** returns `CALayer` by default. A subclass overrides it to get a specialised layer as its own backing layer, for example `CAGradientLayer` for a card background or `CAShapeLayer` for a progress ring. UIKit reads it only once, early in the view's creation, so it is a static choice per view class, not a switch you flip later. Apple's own example is `CATiledLayer`, which a view showing a very large scrollable area returns so its content is drawn in tiles. Inside the view you then cast `layer` to that type and configure it; the gradient or shape follows the view's bounds automatically because it *is* the view's layer, not a sublayer you must resize in `layoutSubviews()`. ## What cornerRadius rounds and what it leaves alone **`cornerRadius`** defaults to `0`. A positive value rounds the **background color** and the **border**. It does not, by default, apply to the image in the layer's **`contents`**, which is where a `UIImageView`'s picture ends up. So an image view with a radius of half its width shows a rounded grey background behind a square photo whose corners still stick out. Two related properties refine the shape: - **`maskedCorners`** (iOS 11) chooses which corners take the radius; it defaults to all four. - **`cornerCurve`** (iOS 13) chooses between `.circular`, the default, and `.continuous`, a curve that eases into the straight edges. ## masksToBounds: the implicit mask **`masksToBounds`** defaults to `false`. When it is `true`, Core Animation applies an **implicit mask** matching the layer's bounds, corner radius included, and everything the layer renders is clipped to it: the contents image, the sublayers, and anything drawn outside the bounds. If the layer also has an explicit `mask` layer, the two masks are multiplied. On a view, `clipsToBounds` gives the same clipping. | Settings on an image view's layer | Background | Picture | Sublayers outside bounds | Shadow | |---|---|---|---|---| | `cornerRadius = 40` only | rounded | square corners | visible | visible | | `cornerRadius = 40`, `masksToBounds = true` | rounded | clipped to the circle | clipped | clipped away | | `masksToBounds = true` only | square | clipped to the rectangle | clipped | clipped away | ## Rounding and shadow on one card Because the bounds mask clips everything outside the bounds, a layer cannot both clip its content to a rounded shape and show a shadow around that shape. The usual structure splits the jobs: 1. An outer view or layer with `masksToBounds` left `false` draws the shadow, ideally with a `shadowPath` matching the rounded outline. 2. An inner view with the same `cornerRadius` and `masksToBounds = true` holds the image. 3. Both read the same radius constant so the curves line up. ## Common mistakes - Expecting `cornerRadius` alone to crop a photo into a circle. - Trying to assign a new layer to `view.layer` instead of overriding `layerClass`. - Adding a `CAGradientLayer` as a sublayer, then forgetting to resize it when the view's bounds change, when overriding `layerClass` would have kept it in step. - Turning on `masksToBounds` for a card and then wondering where its shadow went. - Setting the view as the delegate of some other layer, which Apple's documentation tells you never to do. In an interview, the strong answer names the ownership (view owns one layer and is its delegate), the extension point (`layerClass`), and the precise split between what `cornerRadius` rounds and what `masksToBounds` clips.

  • Why does a rounded image with a drop shadow usually take two views or two layers?
    The `masksToBounds` mask clips everything the layer renders, including a shadow drawn outside its bounds, so a clipped layer loses its shadow. Put the shadow on an outer view that does not clip, give it a `shadowPath` with the same rounded outline, and nest the clipped image view inside it with the same radius.
  • What do maskedCorners and cornerCurve add to cornerRadius?
    `maskedCorners`, available since iOS 11, picks which of the four corners take the radius, so a sheet can round only its top corners; it defaults to all four. `cornerCurve`, since iOS 13, picks the curve: `.circular` by default or `.continuous`, which blends more gradually into the straight edges.
  • Can a view create its CAShapeLayer as a sublayer instead of overriding layerClass?
    Yes, but then the shape layer is a separate object you must size yourself, usually in `layoutSubviews()`, and keep in step with the view's bounds. Overriding `layerClass` makes the shape layer the view's backing layer, so it always has the view's bounds and needs no extra layout code.

  • Setting cornerRadius alone crops a layer's image contents to the rounded shape.
  • You replace a view's backing layer by assigning a new CALayer to view.layer.
  • masksToBounds clips only sublayers and never the layer's own contents image.
  • Overriding layerClass can switch a view's layer type at any point after creation.
  • Making a view the delegate of another standalone CALayer is a harmless shortcut.
open as a page

In Core Animation, why does a breathing ring's CABasicAnimation on strokeEnd snap back to empty when it ends, and what are the two fixes?

level: middleimportance: must knowfreq 75%

basics

~20 s

An explicit CABasicAnimation changes only the displayed value, not the layer's model strokeEnd, and is removed when it ends, so the ring jumps back. Set the model value before adding the animation, or keep the animation with isRemovedOnCompletion false and fillMode forwards.

open as a page

In Core Animation, why does changing a standalone CAShapeLayer's strokeEnd animate by itself while a view's backing layer does not, and how does CATransaction control it?

level: middleimportance: should knowfreq 60%

basics

~20 s

Changing an animatable property on a standalone layer runs its implicit action, a 0.25-second animation by default. A view's backing layer asks the view, its delegate, which supplies none outside a UIView animation block. CATransaction sets duration, timing, completion, or disables actions.

open as a page

In Core Animation, taps on the visible edge of a breathing app's bubble layer miss while it shrinks on an exhale; why, and how do you hit-test what is on screen?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Hit testing a layer reads the model layer, which already holds the animation's end values, while the screen shows the presentation layer. Call presentation() on the moving layer and hit-test or read its frame there, with the touch converted into the superlayer's coordinates.

open as a page

In Core Animation, why do technique cards with layer shadows stutter while scrolling, and when do shadowPath and shouldRasterize fix it or make it worse?

level: seniorimportance: should knowfreq 45%

basics

~20 s

With shadowPath nil, a layer's shadow is built from its composited alpha, so the content must render before the shadow, frame after frame. Setting shadowPath supplies the outline; shouldRasterize caches a bitmap that helps unchanging content and hurts changing content.

open as a page