欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

YYText源码解读-YYText同步/异步渲染流程(一)—UIView与CALayer

程序员文章站 2023-12-23 13:12:52
...

文章转载自40K CLUB APP

一、CALayer官方文档

Layers are often used to provide the backing store for views but can also be used without a view to display content. A layer’s main job is to manage the visual content that you provide but the layer itself has visual attributes that can be set, such as a background color, border, and shadow. In addition to managing visual content, the layer also maintains information about the geometry of its content (such as its position, size, and transform) that is used to present that content onscreen. Modifying the properties of the layer is how you initiate animations on the layer’s content or geometry. A layer object encapsulates the duration and pacing of a layer and its animations by adopting the CAMediaTiming protocol, which defines the layer’s timing information.
If the layer object was created by a view, the view typically assigns itself as the layer’s delegate automatically, and you should not change that relationship. For layers you create yourself, you can assign a delegate object and use that object to provide the contents of the layer dynamically and perform other tasks. A layer may also have a layout manager object (assigned to the layoutManager property) to manage the layout of subviews separately.

二、UIView和CALayer的关系

由官方文档和平时的知识积累和开发经验可知,Layer是View的一个属性,Layer由View初始化时自动创建,而且View会自动将自己设置为Layer的代理。

同时CALayer提供了一个+layerClass方法,我们可以通过重写这个方法返回一个我们自定义的CALayer的子类的类型,这时,UIView会自动创建一个我们自定义子类类型的Layer作为View的根Layer。

+ (Class)layerClass;

三、CALayer的一些属性

1 presentationLayer

通过官方文档可知,Layer的作用是为View提供后备存储,什么意思呢?Layer的主要工作是提供视觉内容,当我们修改Layer的属性时,会启动隐式动画,动画是有过渡时间的。如果一个动画还没有结束,我们提交了新的属性,这时会发生什么?会在前一个动画结束后,才会刷新新的属性。也就是说Layer的属性不是实时显示在屏幕上的,那么我们怎样获取此时屏幕上属性值呢?

可查看官方文档中对presentationLayer的描述,这个值是最接近此时屏幕显示的属性值的Layer。

2 contents

The default value of this property is nil.
If you are using the layer to display a static image, you can set this property to the CGImage containing the image you want to display. (In macOS 10.6 and later, you can also set the property to an NSImage object.) Assigning a value to this property causes the layer to use your image rather than create a separate backing store.

当我们把这个值设置为一个CGImage对象时,Layer就会显示为一张图片。

3 display

这个方法不要主动调用,通过调用Layer的代理的display(_:)方法或者Layer的draw(in:) 方法,会自动调用改方法。这个方法的作用是设置contents属性。我们可以重写这个方法,来设置自定义的contents。

4 setNeedsDisplay

Marks that -display needs to be called before the layer is next committed.

从Xcode的接口声明中可以指导,该方法不会立即调用display方法,而是做一个标记,在Layer下一次提交时,先调用display方法。

5 defaultValue(forKey:)

指定默认属性值。

四、总结

我们了解了以上几个属性和方法的作用,就能轻松的知道YYtext的同步/异步渲染流程了。

文章转载自40K CLUB APP

相关标签: 富文本

上一篇:

下一篇: