kavalerov
kavalerov

Reputation: 390

Draw several UIViews on one layer

Is it possible to draw several UIViews with custom drawing on single CALayer so that they dont have backing store each?

UPDATE:

I have several uiviews of the same size which have same superview. Right now each of them has custom drawing. And because of big size they create 600-800 mb backing stores on iPad 3. so i want to compose their output on one view and have several times less memory consumed.

Upvotes: 1

Views: 784

Answers (2)

Bobjt
Bobjt

Reputation: 4100

Since the views will share the same backing store, I assume you want them to share the same image that results from the layer's custom drawing, right? I believe this can be done with something similar to:

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

Upvotes: 1

Bastian
Bastian

Reputation: 10433

Every view has it's own Layer and you can't change that.

You could enable shouldRasterize to flatten a view hierarchy, which might help in some cases, but that needs gpu memory.

another way could be to create an image context and merge the drawings into the image and set that as the layer content.

in one of the wwdc session videos of last year which was about drawing showed a drawing app where many strokes were transfered into a image to speed up drawing.

Upvotes: 3

Related Questions