1

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

Ted
  • 3,805
  • 14
  • 56
  • 98

4 Answers4

4

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];
Vytis
  • 1,170
  • 8
  • 13
  • Vytis, everything makes sense here except for `UIImage *snapshot = [interestingView snapshotImage];` Xcode complains: `Use of undeclared identifier interestingView’`. Exactly how did you declare this ? – Greg May 21 '17 at 23:13
  • 1
    `interestingView` is the view you want to take the snapshot image of. So for example if you want to take a snapshot of a view controller's view you will have `UIImage *snapshot = [self.view snapshotImage];` somewhere in your UIViewController code. – Vytis May 22 '17 at 09:16
2

Swift 5 , easy to call

extension UIView {
    var asImg: UIImage? {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}
dengApro
  • 3,848
  • 2
  • 27
  • 41
1

It is indeed possible, using Core Graphics' rendering functions you render the view into a context, and then initialize an image with the contents of that context. See the answer to this question for a good technique.

Community
  • 1
  • 1
Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
0

Here is a swift 2.x version for Vytis example

extension UIView {

    func snapshotImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0)
        self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let resultingImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resultingImage
    }
}
Asdrubal
  • 2,421
  • 4
  • 29
  • 37