Flatten CALayer sublayers into one layer

2019-02-11 03:54发布

In my app I have one root layer, and many images which are sublayers of rootLayer. I'd like to flatten all the sublayers of rootLayer into one layer/image, that don't have any sublayers. I think I should do this by drawing all sublayers in core graphics context, but I don't know how to do that.

I hope you'll understand me, and sorry for my English.

2条回答
叼着烟拽天下
2楼-- · 2019-02-11 04:27

Do you still want the layer to be interactive? If not, call -renderInContext: and show the bitmap context.

查看更多
Anthone
3楼-- · 2019-02-11 04:41

From your own example for Mac OS X:

CGContextRef myBitmapContext = MyCreateBitmapContext(800,600);
[rootLayer renderInContext:myBitmapContext];
CGImageRef myImage = CGBitmapContextCreateImage(myBitmapContext);
rootLayer.contents = (id) myImage;
rootLayer.sublayers = nil;
CGImageRelease(myImage);

iOS:

UIGraphicsBeginImageContextWithOptions(rootLayer.bounds.size, NO, 0.0);
[rootLayer renderInContext: UIGraphicsGetCurrentContext()];
UIImage *layerImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
rootLayer.contents = (id) layerImage.CGImage;
rootLayer.sublayers = nil;

Also note the caveat in the docs:

The Mac OS X v10.5 implementation of this method does not support the entire Core Animation composition model. QCCompositionLayer, CAOpenGLLayer, and QTMovieLayer layers are not rendered. Additionally, layers that use 3D transforms are not rendered, nor are layers that specify backgroundFilters, filters, compositingFilter, or a mask values.

查看更多
登录 后发表回答