I have a graphics app I am writing that has a UIView that has several UIImageViews as subviews added to it over time. I want to flatten all these subviews for performance reasons as it is slowing down over time. What is the simplest way to "flatten" these layers.
Asked
Active
Viewed 730 times
1
-
It's not clear to me what you mean by "flatten." Can you describe the performance limitations you're encountering and why "flattening" the views will fix these problems? Is flattening a graphical distortion, or do you mean combining the views into a single view? – Neil Mix Oct 29 '09 at 03:07
-
Neil, I'm pretty sure he means "composite all the separate images into one image" (which is often called flattening in Photoshop, et al when dealing with layers). My response is based on that assumption – Matt Gallagher Oct 29 '09 at 03:32
1 Answers
2
Create a new bitmap context:
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
CGContextRef newContext =
CGBitmapContextCreate(
NULL,
viewContainingAllUIImageViews.frame.size.width,
vViewContainingAllUIImageViews.frame.size.height,
8,
viewContainingAllUIImageViews.frame.size.width,
colorspace,
0);
CGColorSpaceRelease(colorspace);
Paint the appropriate background into the context:
CGContextSetRGBFillColor(newContext, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(newContext, CGRectMake(0, 0, viewContainingAllUIImageViews.frame.size.width, vViewContainingAllUIImageViews.frame.size.height));
Get the CGImage
property of each image that your UIImageView
contains and draw all of the images into this single image:
CGContextDrawImage(newContext, oneOfTheSubImageViews.frame, oneOfTheSubImageViews.image.CGImage);
Convert the bitmap context back into an image:
CGImageRef newImage = CGBitmapContextCreateImage(newContext);
UIImage *flattenedImage = [UIImage imageWithCGImage:newImage];
Then CFRelease
newContext
, newImage
, use the UIImage
in a UIImageView
and discard all other UIImageView
s.

Matt Gallagher
- 14,858
- 2
- 41
- 43
-
Thanks Matt. That has been very helpfull. I am integrating parts of that into my code. – Steven MCD Oct 30 '09 at 14:36
-
I found one more option: to just render the entire parent view's layer instead of looping through each subview: http://stackoverflow.com/questions/3869692/iphone-flattening-a-uiimageview-and-subviews-to-image-blank-image either way should work fine though. – taber Aug 11 '11 at 15:01