在一层上绘制多个 UIView

Posted

技术标签:

【中文标题】在一层上绘制多个 UIView【英文标题】:Draw several UIViews on one layer 【发布时间】:2012-10-18 21:53:18 【问题描述】:

是否可以在单个 CALayer 上使用自定义绘图绘制多个 UIView,这样它们每个都没有后备存储?

更新:

我有几个相同大小的 uiview,它们具有相同的超级视图。现在他们每个人都有自定义绘图。而且由于它们的尺寸很大,它们在 iPad 3 上创建了 600-800 mb 的后备存储。所以我想在一个视图上组合它们的输出,并且消耗的内存要少几倍。

【问题讨论】:

我会说不,因为当 CALayer 附加到视图时,需要将视图设置为图层的委托。由于委托在 Cocoa 设计中是一对一的关系,所以对象(例如 CALayers)不能同时拥有多个委托,因此不太可能同时使用它们在多个视图中显示。跨度> 【参考方案1】:

每个视图都有自己的图层,您无法更改它。

您可以启用 shouldRasterize 来展平视图层次结构,这在某些情况下可能会有所帮助,但这需要 gpu 内存。

另一种方法是创建图像上下文并将绘图合并到图像中并将其设置为图层内容。

在去年的一个 wwdc 会议视频中,一个关于绘图的视频展示了一个绘图应用程序,其中许多笔画被转移到图像中以加快绘图速度。

【讨论】:

其实这就是我现在想要做的——使用图像上下文。【参考方案2】:

由于视图将共享相同的后备存储,我假设您希望它们共享由图层的自定义绘图产生的相同图像,对吧?我相信这可以通过类似的方式来完成:

// create your custom layer
MyCustomLayer* layer = [[MyCustomLayer alloc] init];

// create the custom views
UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake( 0, 0, layer.frame.size.width, layer.frame.size.height)];
UIView* view2 = [[UIView alloc] initWithFrame:CGRectMake( 100, 100, layer.frame.size.width, layer.frame.size.height)];

// have the layer render itself into an image context
UIGraphicsBeginImageContext( layer.frame.size );
CGContextRef context = UIGraphicsGetCurrentContext();
[layer drawInContext:context];
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// set the backing stores (a.k.a the 'contents' property) of the view layers to the resulting image
view1.layer.contents = (id)image.CGImage;
view2.layer.contents = (id)image.CGImage;

// assuming we're in a view controller, all those views to the hierarchy
[self.view addSubview:view1];
[self.view addSubview:view2];

【讨论】:

以上是关于在一层上绘制多个 UIView的主要内容,如果未能解决你的问题,请参考以下文章

如何在两个单独的图层上绘制iOS,coregraphics

如何将子层与 UIView 一起移动?

传单:如何仅在一层上显示标记或图例?

如何绘制部分边框?

R ggplot2:在不同图层上绘制数据子集时保持原始颜色和组级顺序

在一张图中绘制多个箱线图