4

I want to convert a UIView to a UIImage

- (UIImage *)renderToImage:(UIView *)view {
  if(UIGraphicsBeginImageContextWithOptions != NULL) {
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
  } else {
    UIGraphicsBeginImageContext(view.frame.size);
  }

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

Two questions:

  1. I have subviews on my view. Is there a way to create an image of the view without any of the subviews? Ideally id like to not have to remove them just to add them back later.

  2. Also, it isn't rendering the images properly on retina devices. I followed the advice here to use context with options but it did not help. How to capture UIView to UIImage without loss of quality on retina display

Community
  • 1
  • 1
user1802143
  • 14,662
  • 17
  • 46
  • 55

2 Answers2

2

You have to hide the subviews that you not want to be in the image of view. Below is the Method that render image of view for retina devices too.

- (UIImage *)imageOfView:(UIView *)view
{

  // This if-else clause used to check whether the device support retina display or not so that   
  // we can render image for both retina and non retina devices. 

    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) 
       {
               UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
       } else {
                UIGraphicsBeginImageContext(view.bounds.size);
       }


    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}
max_
  • 24,076
  • 39
  • 122
  • 211
Anuj
  • 820
  • 4
  • 11
0
- (CGImageRef)toImageRef
{
    int width = self.frame.size.width;
    int height = self.frame.size.height;
    CGContextRef ref = CGBitmapContextCreate(NULL, width, height, 8, width*4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast);
    [self drawRect:CGRectMake(0.0, 0.0, width, height) withContext:ref];
    CGImageRef result = CGBitmapContextCreateImage(ref);
    CGContextRelease(ref);
    return result;
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    // move your drawing commands from here...
    [self drawRect:rect withContext:context];
}

- (void)drawRect:(CGRect)rect withContext:(CGContextRef)context
{
    // ...to here
}
marcelnijman
  • 586
  • 4
  • 10