Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving UIView contents in iOS 4 with real size of the images inside (i.e. scale contentes up for save)

I have an UIView with many UIImageViews as subviews. The app runs on iOS4 and I use images with retina display resolution (i.e. the images load with scale = 2)

I want to save the contents of the UIView ... BUT ... have the real size of the images inside. I.e. the view has size 200x200 and images with scale=2 inside, I'd like to save a resulting image of 400x400 and all the images with their real size.

Now what comes first to mind is to create a new image context and load again all images inside with scale=1 and that should do, but I was wondering if there is any more elegant way to do that? Seems like a waist of memory and processor time to reload everything again since it's already done ...

p.s. if anyone has an answer - including code would be nice

like image 873
Marin Todorov Avatar asked Nov 18 '10 09:11

Marin Todorov


1 Answers

Implementation for rendering any UIView to image (working also for retina display).

helper.h file:

@interface UIView (Ext) 
- (UIImage*) renderToImage;
@end

and belonging implementation in helper.m file:

#import <QuartzCore/QuartzCore.h>

@implementation UIView (Ext)
- (UIImage*) renderToImage
{
  // IMPORTANT: using weak link on UIKit
  if(UIGraphicsBeginImageContextWithOptions != NULL)
  {
    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
  } else {
    UIGraphicsBeginImageContext(self.frame.size);
  }

  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();  
  return image;
}

0.0 is the scale factor. The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.

QuartzCore.framework also should be put into the project because we are calling function on the layer object.

To enable weak link on UIKit framework, click on the project item in left navigator, click the project target -> build phases -> link binary and choose "optional" (weak) type on UIKit framework.

Here is library with similar extensions for UIColor, UIImage, NSArray, NSDictionary, ...

like image 111
Krešimir Prcela Avatar answered Sep 22 '22 18:09

Krešimir Prcela