Skip to content

Instantly share code, notes, and snippets.

@JigarM
Created November 16, 2016 13:32
Show Gist options
  • Save JigarM/8d7112517640f905efabefb55f46917b to your computer and use it in GitHub Desktop.
Save JigarM/8d7112517640f905efabefb55f46917b to your computer and use it in GitHub Desktop.
Rendering any UIViews into UIImage in one line Raw => From jamztang (https://gist.github.com/jamztang/1578446)
//
//Reference link : https://gist.github.com/jamztang/1578446
//
#import <UIKit/UIKit.h>
@interface UIView (ViewToImage)
// - [UIImage toImage]
//
// Follow device screen scaling. If your view is sized 320 * 480,
// it renders 320 * 480 on non-retina display devices,
// and 640 * 960 on retina display devices
// Use this option for making high resolution view elements snapshots to display on retina devices
- (UIImage *)toImage;
// - [UIImage toImageWithScale]
//
// Force rendering in a given scale. Commonly used will be "1".
// Good for output or saving a static image with the exact size of the view element.
- (UIImage *)toImageWithScale:(CGFloat)scale;
// - [UIImage toImageWithScale:legacy:]
//
// Set legacy to YES to force use the old API instead of
// iOS 7's drawViewHierarchyInRect:afterScreenUpdates: API
- (UIImage *)toImageWithScale:(CGFloat)scale legacy:(BOOL)legacy;
@end
#import "UIView-ViewToImage.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIView (ViewToImage)
static BOOL _supportDrawViewHierarchyInRect;
+ (void)load {
if ([self instancesRespondToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
_supportDrawViewHierarchyInRect = YES;
} else {
_supportDrawViewHierarchyInRect = NO;
}
}
- (UIImage *)toImage {
return [self toImageWithScale:0];
}
- (UIImage *)toImageWithScale:(CGFloat)scale {
UIImage *copied = [self toImageWithScale:scale legacy:NO];
return copied;
}
- (UIImage *)toImageWithScale:(CGFloat)scale legacy:(BOOL)legacy {
// If scale is 0, it'll follows the screen scale for creating the bounds
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, scale);
if (legacy || ! _supportDrawViewHierarchyInRect) {
// - [CALayer renderInContext:] also renders subviews
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
} else {
[self drawViewHierarchyInRect:self.bounds
afterScreenUpdates:YES];
}
// Get the image out of the context
UIImage *copied = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Return the result
return copied;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment