Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chhoda

macrumors 6502
Original poster
Oct 25, 2008
285
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
 
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?
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.