tags:

views:

85

answers:

1
+1  Q: 

Flatten subviews

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.

+2  A: 

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 UIImageViews.

Matt Gallagher
Thanks Matt.That has been very helpfull. I am integrating parts of that into my code.
Steven MCD