可以从UIView复制CALayer吗? [英] Possible to copy CALayer from UIView?

查看:60
本文介绍了可以从UIView复制CALayer吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的设置:我有一个CALAyer,我想向其中添加子层。我通过设置UILabel来创建这些子层,然后将UILables层添加到我的主层。当然,这会使沉重的UILabel对象在后台徘徊。是否可以从UIView中获取包含其所有内容的图层,并摆脱UIView本身?
我已经尝试过:

Here's my setup: I have a CALAyer to which I want to add sublayers. I create these sublayers by setting upa UILabel and then adding the UILables layer to my main layer. Of course this leaves the heavy UILabel object hovering around in the background. Is it possible to get the layer with all its content from a UIView and get rid of the UIView itself? I already tried this:

UILabel* label;
[...]
[mainLayer addSublayer:[label.layer copy]];
[label release];

但是,每当我释放UIView时,该层的内容也会被删除。这是否有可能,还是UIView的图层始终需要UIView本身来显示其内容?我认为该层是UIView绘制到的一种画布。我想我可能会错认为:)

But whenever I release the UIView, the content of the layer is also removed. Is this even possible or does the UIView's layer always need the UIView itself to show it's content? I thought of the layer as a kind of canvas, to which the UIView paints. I guess I could be wrong with this assumption :)

推荐答案

我不明白为什么您无法复制一层。诚然,图层是UIView的组成部分。但最终,它只是具有多个属性的另一个对象。

I can't understand why you wouldn't be able to copy a layer. True a layer is an "integral part" of a UIView. But in the end it is just another object with several properties.

实际上,CALayer有一种方法称为:

Actually there is a method for CALayer called:

- (id)initWithLayer:(id)layer

但这并不是要复制图层。 (您可以阅读Apple的文档以了解其原因)

But it isn't intended to make a copy of a layer. (You can read Apple's docs for the reasoning why)

CALayer不符合NSCopying,因此有两种选择:

CALayer does not conform to NSCopying, so you have two options:


  1. 子类化并实现
    copyWithZone:(并符合
    NSCopying)

  2. 编写一个方法/函数
    将返回CALayer的副本

无论选择哪种方式,您要问的问题是:您要复制CALlayer的哪些属性?

Regardless of which way you choose, the question you have to ask is: Which properties of the CALlayer do you want to copy?

假设您只复制内容和框架:

Let's say you want to copy just the contents and frame:

CALayer copyLayer = [CALayer layer];

copyLayer.contents = theLayerToBeCopied.contents;
copyLayer.frame = theLayerToBeCopied.frame;

return copyLayer;

您可以遍历并复制图层的每个属性,也可以复制所需的属性。放入CALayer类别可能是一个好方法。

You could go through and copy every property of the layer, or just copy the ones you need. Might be a good method to put in a CALayer category.

这篇关于可以从UIView复制CALayer吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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