Possible to copy CALayer from UIView?

别来无恙 提交于 2019-12-10 14:02:27

问题


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];

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 :)


回答1:


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.

Actually there is a method for CALayer called:

- (id)initWithLayer:(id)layer

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

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

  1. Subclass it and implement "copyWithZone:" (and conform to NSCopying)
  2. Write a method/function that will return a "copy" of a CALayer

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;

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.




回答2:


It is not possible: a layer is a property of a UIView. Therefore, when you release the UIView, its layer is gone. Your idea of thinking of the layer as a kind of canvas is not wrong. But, the layer is an integral part of its UIView.




回答3:


UILabel really isn't a very complex control. I suggest you give up this line of attack and learn how to draw what you want using Quartz into a fresh CGImage. You can then assign this to the contents property of the CALayer without having to worry about all this other stuff.




回答4:


You can also circumvent UILabel entirely and create your text with a CATextLayer.




回答5:


use CAReplicatorLayer, you will be able to completely replicate that layer



来源:https://stackoverflow.com/questions/961976/possible-to-copy-calayer-from-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!