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
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];
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)
}
}
}
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.
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
}
}