截取web页面获取长图

时间:2019-02-21
本文章向大家介绍截取web页面获取长图,主要包括截取web页面获取长图使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在项目中有时会用到 截取web页面的长图并分享 ,一般截取只能截取屏幕显示部分,如果截取未显示部分就需要截取长图了。

//方法调用

  CGRect snapshotFrame = CGRectMake(0, 0, _web.scrollView.contentSize.width, _web.scrollView.contentSize.height);

    UIEdgeInsets snapshotEdgeInsets = UIEdgeInsetsZero;

    UIImage *longImage = [self captureImagesViewFromRect:snapshotFrame withCapInsets:snapshotEdgeInsets];

   longImage 就是截取的长图

//获取长图主要方法

// 生成长图
- (UIImage *)captureImagesViewFromRect:(CGRect)rect withCapInsets:(UIEdgeInsets)capInsets {
    
    CGFloat scale = [UIScreen mainScreen].scale;
    
    CGSize boundsSize = self.web.bounds.size;
    CGFloat boundsWidth = boundsSize.width;
    CGFloat boundsHeight = boundsSize.height;
    
    CGSize contentSize = self.web.scrollView.contentSize;
    CGFloat contentHeight = contentSize.height;
   
    CGPoint offset = self.web.scrollView.contentOffset;
    
    [self.web.scrollView setContentOffset:CGPointMake(0, 0)];
    
    NSMutableArray *images = [NSMutableArray array];
    while (contentHeight > 0) {
        UIGraphicsBeginImageContextWithOptions(boundsSize, NO, [UIScreen mainScreen].scale);
        // 在当前上下文中渲染出webView
        // 如果取webView.scrollView.layer则会超出一屏的数据不能显示,只能显示白色区域块
        [self.web.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [images addObject:image];
        
        CGFloat offsetY = self.web.scrollView.contentOffset.y;
        // 设置webView的偏移量
        [self.web.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];
        contentHeight -= boundsHeight;
    }
    
    
    [self.web.scrollView setContentOffset:offset];
    
    CGSize imageSize = CGSizeMake(contentSize.width * scale,
                                  contentSize.height * scale);
    UIGraphicsBeginImageContext(imageSize);
    [images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
        [image drawInRect:CGRectMake(0,
                                     scale * boundsHeight * idx,
                                     scale * boundsWidth,
                                     scale * boundsHeight)];
    }];
    // 截取当前上下文生成Image
    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageView *snapshotView = [[UIImageView alloc]initWithFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)];
    
    snapshotView.image = [fullImage resizableImageWithCapInsets:capInsets];
    
    return snapshotView.image;
}