从 CALayers 获取位图,renderInContext 的任何替代方案
我有许多 CALayer,它们是在我的应用程序运行时动态创建的,并且我需要能够生成这些的单个位图,稍后将对其进行屏蔽。
当我需要创建蒙版时,CALayers 已经绘制到背景(也使用 shouldRasterize = YES),并且使用 renderInContext 我能够获取位图。然而,随着 CAlayer 数量的增加,renderInContext 引起的停顿变得越来越长。是否有其他方法可以用来 renderInContext,或者有其他方法可以使用它来阻止我的应用程序暂时冻结?
理想的情况是直接从内存/缓冲区/缓存访问已经绘制的像素数据,而不使用 OpenGL,但我不确定这是否可以通过 CoreAnimation 实现。
谢谢,任何额外的信息都会非常有用!
I have many CALayers which are created on the fly while my app is running, and I need to be able to produce a single bitmap of these, which will later be masked.
When I need to create the mask, the CALayers are already drawn to the background (also using shouldRasterize = YES) , and using renderInContext I am able to get a bitmap. However, as the amount of CAlayers increases, the pause caused by renderInContext gets longer and longer. Is there an alternative I can use to renderInContext, or an alternative way I can use it to stop my app temporarily freezing?
The ideal would be to access the already drawn pixel data directly from memory/buffer/cache without using OpenGL, but I am unsure if this is possible with CoreAnimation.
Thanks, any additional information at all would be very useful!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rob 认为
renderInContext:
是此处使用的正确方法,这是正确的。在上下文中渲染实际上是将图层的像素数据渲染到上下文中。这是一个示例应用程序,它将在后台线程上绘制 10,000 个图层...该应用程序执行以下操作:
这是代码...
首先,创建一个带有很多层:
第二,创建一个方法来启动计时器,然后触发渲染...
第三,创建一个带有回调方法的渲染循环,该回调方法在渲染完成后将图像显示在屏幕上。
注意:如果您的图层并非全部位于同一个子图层中,您可以轻松调用
for
循环,将上下文转换为每个 CALayer 的原点或从每个 CALayer 的原点进行转换,并将每个图层单独绘制到上下文本身中。我运行它,得到以下输出:
Rob is right about
renderInContext:
being the right method to use here. Render in context does actually render the layer's pixel data into a context. Here's a sample application that will draw 10,000 layers on a background thread...The application does the following:
Here is the code...
First, create a subview with a lot of layers:
Second, create a method that will start a timer and then triggers the render...
Third, create a render loop with a callback method that puts an image on the screen after rendering is completed.
NOTE: if your layers aren't all in the same sublayer, you can easily call a
for
loop that translates the context to and from the origin of each CALayer and draw each layer individually into the context itselfWhen I run this I get the following output:
renderInContext:
是这里最好的工具,但您不需要在主线程上运行它。只需将其移至后台线程,它就会停止冻结您的应用程序。renderInContext:
is the best tool here, but you don't need to run it on the main thread. Just move this to a background thread and it'll stop freezing your app.