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?
answer
- every view owns one layer
- layerClass picks its type
- background and border, not contents
- an implicit mask matching the bounds
- that mask also cuts the shadow
basics
~20 sEvery 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 sA `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 linesimport 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
Recall that each view has one backing CALayer, that cornerRadius rounds background and border, and that masksToBounds or clipsToBounds is what clips the picture.
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.
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.
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.