ios - 在 iOS 上,当我们从上下文中创建一个层并获取层的上下文后,这些上下文如何相互关联?

标签 ios core-graphics calayer quartz-2d graphicscontext

我们可以从当前图形上下文创建一个层,然后获取层的上下文:

CGContextRef context = UIGraphicsGetCurrentContext();

CGLayerRef layer = CGLayerCreateWithContext(context, 
                                            CGSizeMake(self.frame.size.width,
                                                self.frame.size.height), NULL);

CGContextRef contextOfLayer = CGLayerGetContext(layer);

所以我们现在有 2 个上下文:contextcontextOfLayer。这两个上下文如何相互关联? contextOfLayer 实际上是 context 的一部分并且 context 有一个层上下文指针数组吗?如果我使用 NSLog(@"%p", ...) 打印出他们的地址,他们有不同的地址,所以他们不是同一个对象。而且我认为 contextOfLayer 不会影响上下文堆栈,所以它只是一个独立的上下文,它本身就“存在于那里”吗?

最佳答案

如果您了解 CGLayer 的基本原理,将会有所帮助。 CGLayer 是一种优化,当您将相同的内容重复绘制到特定类型的上下文中时。

(例如:具有特定格式的位图上下文——例如 32 位 RGBA——或 PDF 上下文等)

当您创建 CGLayer 时,您将其传递给您打算将 CGLayer 绘制到其中的上下文。这让 CGLayer 针对这种上下文优化自身。

稍后,如果将 CGLayer 绘制到该上下文中,或者绘制到具有相同格式的不同上下文中,绘制速度会更快。

如果将 CGLayer 绘制到具有不同格式的上下文中,绘图仍然有效,并且不会出现错误。但是,它可能不会比直接绘制到该上下文中更快。

documentation for CGLayerCreateWithContext说:

context

The graphics context you want to create the layer relative to. The layer uses this graphics context as a reference for initialization.

这意味着该层将给定的 context 作为引用。这并不一定意味着 context 存储在 CGLayer 中,或者被永久引用。可能是,但您无法判断——这是一个内部实现细节。

documentation for CGLayerGetContext

The context that’s returned is the context for the layer itself, not the context that you specified when you created the layer.

因此您应该期望 context != contextOfLayer

同样,API 没有指定任何关于这些上下文如何相互关联的信息——它们可能在内部相互引用,也可能不相互引用。作为 API 的用户,我们不应该做任何假设。

具体回答您的问题:

Is contextOfLayer actually part of context and context has a array of layer context pointers?

我们不知道,也无法找出答案。作为 API 的用户,我们不应该编写任何采用这种或那种方式的代码。

I think contextOfLayer doesn't affect the context stack, so is it just an independent context just kind of "exist out there" by itself?

是的,它是一个独立的上下文。 UIKit 中的“上下文栈”是一个更高层次的概念。 CoreGraphics 中的 CGLayer 是一个较低级别的 API,它对 UIKit 一无所知。

关于ios - 在 iOS 上,当我们从上下文中创建一个层并获取层的上下文后,这些上下文如何相互关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10672691/

相关文章:

objective-c - 在 CALayer 或 CGImage 上实现径向 alpha 渐变?

ios - 如何在 Swift 中的 UIActivityViewController 中设置电子邮件收件人。可能吗?

ios - 更改 LineChartData 标签的颜色

ios - 更改 Anypic Assets

objective-c - 检查 CALayer 是否已经添加为子层

iOS 从 UIView 创建 PDF

iphone - 如何在iPhone中更改UITextView最后输入的文本颜色?

ios - 在 Playground 中加载和注册 CGFonts

Swift - 如何填充路径(不透明路径)

ios - 通过 iOS 创建和导出动画 gif?