UIImage for UIVIew

Discussion in 'iOS Programming' started by chhoda, May 8, 2012.

  1. chhoda macrumors 6502

    Joined:
    Oct 25, 2008
    #1
    i am trying to get UIImage representation of UIView

    Code:
    	UIView *viewForImage = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    	[viewForImage setBackgroundColor:color];
    	
    	UIGraphicsBeginImageContext(viewForImage.bounds.size);
    	[viewForImage.layer renderInContext:UIGraphicsGetCurrentContext()];
    	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
    	UIGraphicsEndImageContext();
    	
    	[viewForImage release];
    	return viewImage;
    
    it used to work in 3.0 in 4.0 i get a warning no renderInContext method found and the image is nil

    why so ? what's the work around ?
    but when i ctrl dblclick the function i go into CALayer.h

    i have added coregraphics and fundation and quartzcore frameworks

    regards
     
  2. robbieduncan, May 8, 2012
    Last edited: May 8, 2012

    robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    I've never had a problem with this category on UIView:

    UIView_RenderToImage.h
    Code:
    #import <UIKit/UIKit.h>
    //
    @interface UIView(RenderToImage)
    
    - (UIImage *) viewAsImage;
    
    @end
    UIView_RenderToImage.m
    Code:
    #import "UIView_RenderToImage.h"
    #import <QuartzCore/CALayer.h> // Prevents compile warning on renderInContext: below
    
    @implementation UIView(RenderToImage)
    
    - (UIImage *) viewAsImage
    {	
    	if (UIGraphicsBeginImageContextWithOptions!=NULL)
    	{
    		UIGraphicsBeginImageContextWithOptions(self.frame.size,NO,0.0); // iOS 4.0: the 0.0 scale will use the correct scale for the device (so 1.0 for all pre-iPhone 4 devices and 2.0 for iPhone 4)
    	}
    	else 
    	{
    		UIGraphicsBeginImageContext(self.frame.size); // iOS < 4.0
    	}
    	// Start an image context the size of the view we want to render
    	[self.layer renderInContext:UIGraphicsGetCurrentContext()]; // Render the label we wanted to use into the image.
    	UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext(); // Get the image
    	UIGraphicsEndImageContext(); // End the rendering
    	return resultingImage;
    }
    
    @end
    Do you have the import that I have commented about preventing a warning?
     

Share This Page