是否可以在drawInContext调用之间保留CALayer的内容? [英] Is it possible to persist the contents of a CALayer between drawInContext calls?

查看:52
本文介绍了是否可以在drawInContext调用之间保留CALayer的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在drawLayer:inContext:调用之间是否有维护CALayer内容的内置功能?现在,我将图层复制到缓冲区中,并在每次我在drawLayer:inContext中调用时从缓冲区中重绘图像:但是我想知道CALayer是否可以自动执行此操作...

Are there any built in abilities to maintain the contents of a CALayer between drawLayer:inContext: calls? Right now I am copying the layer to a buffer and redrawing an image from the buffer every time I called back in drawLayer:inContext: but I'm wondering if CALayer has a way to do this automatically...

推荐答案

我不这么认为。 drawInContext将清除基础缓冲区,以便您可以对其进行绘制。但是,如果放弃 drawInContext drawRect 方法,则可以将layer.contents设置为CGImage,这将被保留。

I don't believe so. The 'drawInContext' will clear the underlying buffer so that you can draw to it. However, if you forego the drawInContext or drawRect methods, you can set your layer.contents to a CGImage and that will be retained.

我个人几乎在所有例程中都这样做。我覆盖-(void)setFrame:(CGRect)frame 来检查帧大小是否已更改。如果已更改,我将使用普通的绘制例程重绘图像,但会重新绘制上下文: UIGraphicsBeginImageContextWithOptions(size,_opaque,0); 。然后,我可以抓取该图像并将其设置为imageCache: cachedImage = UIGraphicsGetImageFromCurrentImageContext(); 。然后,将layer.Contents设置为CGImage。我用它来缓存我的图形,尤其是在新的iPad上,这在许多绘制例程中都很慢,iPad 2甚至不闪烁。

I personally do this for almost all of my routines. I overwrite - (void) setFrame:(CGRect)frame to check to see if the frame size has changed. If it has changed I redraw the image using my normal drawing routines but into the context: UIGraphicsBeginImageContextWithOptions(size, _opaque, 0);. I can then grab that image and set it to the imageCache: cachedImage = UIGraphicsGetImageFromCurrentImageContext();. Then I set the layer.Contents to the CGImage. I use this to help cache my drawings, especially on the new iPad which is slow on many drawing routines the iPad 2 doesn't even blink on.

此方法的其他优点:如果设置单独的共享缓存,则可以在视图之间共享缓存的图像。如果管理好缓存,这确实可以帮助您节省内存。 (提示:我使用NSStringFromCGSize作为共享图像的字典键)。另外,您实际上可以在其他线程上拆分绘图例程,然后在完成后设置图层内容。这样可以防止绘图例程阻塞主线程(在这种情况下,即使设置了新图像,当前图像也可能会被拉伸)。

Other advantages to this method: You can share cached images between views if you set up a separate, shared cache. This can really help your memory footprint if you manage your cache well. (Tip: I use NSStringFromCGSize as a dictionary key for shared images). Also, you can actually spin off your drawing routines on a different thread, and then set your layer contents when it's done. This prevents your drawing routines from blocking the main thread (the current image may be stretched in this case though until the new image is set).

这篇关于是否可以在drawInContext调用之间保留CALayer的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆