iOS截屏

- (UIImage *)capture
{
    UIImage* image = nil;

    UIGraphicsBeginImageContext(TOP_VIEW.bounds.size);
    {
        [TOP_VIEW.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
    }
    UIGraphicsEndImageContext();
    
    if (image != nil) {
        return image;
    }
    return nil;
}

这里TOP_VIEW 是宏定义  

[[UIApplication sharedApplication]keyWindow].rootViewController.view

    UIGraphicsBeginImageContext(TOP_VIEW.bounds.size);

关于这个设置,api中有

UIKIT_EXTERN void     UIGraphicsBeginImageContext(CGSize size);
UIKIT_EXTERN void     UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) NS_AVAILABLE_IOS(4_0);

以上两种设置,经过测试,UIGraphicsBeginImageContextWithOptions 在ios8下进app时会崩溃.用UIGraphicsBeginImageContext则没有这方面问题

 

以上代码会造成不稳定因素...

因此 附上另外一种实现方式

创建UIView的category  

实现以下方法 

 1 -(UIImage *)convertViewToImage
 2 
 3 {
 4     
 5     UIGraphicsBeginImageContext(self.bounds.size);
 6     
 7     [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
 8     
 9     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
10     
11     UIGraphicsEndImageContext();
12     
13     return image;
14     
15 }

然后截图的时候,操作当前view去执行  convertViewToImage即可获得截下来的image对象

posted @ 2016-01-18 15:52  老徐想减肥  阅读(240)  评论(0编辑  收藏  举报