Ted Ted - 4 months ago 17
iOS Question

make a UIView with added subviews into a single image?

I have a view with added subviews. I would like to turn that view with many subviews into a single image or view.

How is that possible?

Thanks

Answer

On iOS7 you can use the new [UIView snapshotViewAfterScreenUpdates:] method.

To support older OS you can render any view into an UIImage with Core Graphics. I use this category on UIView for snapshots:

UView+Snapshot.h:

#import <UIKit/UIKit.h>

@interface UIView (Snapshot)
- (UIImage *)snapshotImage;
@end

UView+Snapshot.m:

#import "UIView+Snapshot.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIView (Snapshot)

- (UIImage *)snapshotImage
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

@end

It requires QuartzCore framework, so make sure to add that to your project.

To use it import the header and:

UIImage *snapshot = [interestingView snapshotImage];
Comments