方法1:本人使用该方法以后截屏的结果总是黑屏
大致的流程就是通过获取上下文,并针对某一个View的Layer层进行渲染,获取上下文中的图片
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale);
else
UIGraphicsBeginImageContext(self.window.bounds.size);
[self.window.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * imgData = UIImagePNGRepresentation(image);
if(imgData)
[imgData writeToFile:@"screenshot.png" atomically:YES];
else
NSLog(@"error while taking screenshot");
方法2:目前正在使用该方法
关键的方法是
<span style="font-size:18px;"><strong>drawViewHierarchyInRect: afterScreenUpdates:</strong></span>
- (UIImage *) screenshot {
CGSize size = CGSizeMake(your_width, your_height);
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
CGRect rec = CGRectMake(0, 0, your_width, your_height);
[_viewController.view drawViewHierarchyInRect:rec afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
原文地址:
http://stackoverflow.com/questions/2200736/how-to-take-a-screenshot-programmatically