UIView 和 CALayer 的关系

1. UIView 和 CALayer 的关系

Layers are not a replacement for your app’s views—that is, you cannot create a visual interface based solely on layer objects. Layers provide infrastructure for your views. Specifically, layers make it easier and more efficient to draw and animate the contents of views and maintain high frame rates while doing so. However, there are many things that layers do not do. Layers do not handle events, draw content, participate in the responder chain, or do many other things. For this reason, every app must still have one or more views to handle those kinds of interactions.
-- The Relationship Between Layers and Views

简单来说,UIView 是对 CALayer 的一个封装:

UIView 和 CALayer 的关系_第1张图片
WWDC 2012 - Session 238 - iOS App Performance: Graphics and Animations

CALayer 负责绘制内容 contents。而 UIView 负责:1. 为 CALayer 提供内容 contents;2. 处理用户事件,参与响应链。

2. CALayer 如何绘制内容

A layer can display a filled background and a stroked border in addition to its image-based contents. The background color is rendered behind the layer’s contents image and the border is rendered on top of that image, as shown in Figure 2-3. If the layer contains sublayers, they also appear underneath the border. Because the background color sits behind your image, that color shines through any transparent portions of your image.

UIView 和 CALayer 的关系_第2张图片
Adding a border and background to a layer

-- Layers Have Their Own Background and Border

3. UIImageView 如何使用 CALayer 绘制图片

既然直接对 CALayer 的 contents 属性赋值一个 CGImage 便能显示图片,所以 UIImageView 就顺利成章地诞生了。实际上 UIImage 就是对 CGImage(或者 CIImage) 的一个轻量封装。

UIView 和 CALayer 的关系_第3张图片
WWDC 2012: iOS App Performance: Graphics and Animations

-- iOS App Performance: Graphics and Animations

参考

  • 离屏渲染优化
  • UIView 绘制渲染机制

你可能感兴趣的:(UIView 和 CALayer 的关系)