Geek@Paris

Save any UIView to PNG files

2011-03-22
//Get the view from a specific window
UIView *view = [[[[[UIApplication sharedApplication] windows] objectAtIndex:1] subviews] lastObject];
 
//Will be used for naming png files
NSInteger index = 0;
 
//Check each subView
for (UIView *subView in [view subviews]) {
	//Find the UIView you need
	if ([subView isKindOfClass:NSClassFromString(@"UIImageView")] || [subView isKindOfClass:NSClassFromString(@"UIThreePartButton")]) {
		//Very important to support retina screen
		if(UIGraphicsBeginImageContextWithOptions != NULL)
			UIGraphicsBeginImageContextWithOptions(subView.frame.size, NO, 0.0);
		else
			UIGraphicsBeginImageContext(subView.frame.size);
 
		//Get the image
		[subView.layer renderInContext:UIGraphicsGetCurrentContext()];
		UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
 
		//Save the image
		NSString *path=[NSHomeDirectory() stringByAppendingFormat:@"/%d.png",index];
		if ([UIImagePNGRepresentation(image) writeToFile:path atomically:YES]) {
			index += 1;
			NSLog(@"Succeeded!");
		}
		else {
			NSLog(@"Failed!");
		}
	}
}
Author:admin | Categories:Dev | Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *


Clickcha - The One-Click Captcha