UIView之截屏操作

来源:互联网 发布:sqlserver数据库备份 编辑:程序博客网 时间:2024/04/28 01:16
//截屏操作全屏
-(UIImage *)snapshotImage{

     // 1.开启上下文
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
     // 2.将控制器view的layer渲染到上下文
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
     // 3.获取图片
    UIImage *snapshotImage=UIGraphicsGetImageFromCurrentImageContext();
     // 4.结束上下文
    UIGraphicsEndImageContext();
    
    return snapshotImage;
}

//自iOS7开始,UIView类提供了一个方法-drawViewHierarchyInRect:afterScreenUpdates:,它允许你截取一个UIView或者其子类中的内容,并且以位图的形式(bitmap)保存到UIImage中,包括UIKit,Quartz,OpenGL ES,SpriteKit等等。在iOS6以及更早的版本中,怎样对UIView截屏从本质来说取决于绘制技术(drawing technique)。

//看下面的代码示例,在iOS7及以上更高版本中,使用-drawViewHierarchyInRect:afterScreenUpdates,截取一个View中内容.
- (UIImage *)snapshotImageAfterScreenUpdates:(BOOL)afterUpdates {
    
    if (![self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
        return [self snapshotImage];
    }
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:afterUpdates];
    UIImage *snap = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snap;

}


//截屏部分区域

- (UIImage *)screenshotWithRect:(CGRect)rect;
{
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (context == NULL)
    {
        return nil;
    }
    
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, -rect.origin.x, -rect.origin.y);
    
    if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
    {
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];
    }
    else
    {
        [self.layer renderInContext:context];
    }
    
    CGContextRestoreGState(context);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


0 0