Webview保存长图

IOS wkwebview保存长图

方案1:
UIImage* image = nil;
  // 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了,调整清晰度。
  UIGraphicsBeginImageContextWithOptions(self.wkWebView.scrollView.contentSize, YES, [UIScreen mainScreen].scale);
  CGPoint savedContentOffset = self.wkWebView.scrollView.contentOffset;
  CGRect savedFrame = self.wkWebView.frame;
  self.wkWebView.scrollView.contentOffset = CGPointZero;
  self.wkWebView.frame = CGRectMake(0, 0, self.wkWebView.scrollView.contentSize.width, self.wkWebView.scrollView.contentSize.height);
  [self.wkWebView.layer renderInContext: UIGraphicsGetCurrentContext()];
  image = UIGraphicsGetImageFromCurrentImageContext();
  self.wkWebView.scrollView.contentOffset = savedContentOffset;
  self.wkWebView.frame = savedFrame;

  UIGraphicsEndImageContext();

  if (image != nil) {
      //保存图片到相册
      UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
  }
方案2:
ZYCaptureScreenShotView *captureView = [[ZYCaptureScreenShotView alloc]initWithFormatter:self.wkWebView.viewPrintFormatter andContentSize:self.wkWebView.scrollView.contentSize];
      UIImage *image = [captureView getContentImage];
      if (image != nil) {
          //保存图片到相册
          UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
      }
方案3:
CGPoint originalOffset = self.wkWebView.scrollView.contentOffset;
    // 当contentSize.height
    NSInteger pageNum = 1;
    if (self.wkWebView.scrollView.contentSize.height > self.wkWebView.bounds.size.height) {
        pageNum = (NSInteger)(floorf((self.wkWebView.scrollView.contentSize.height / self.wkWebView.bounds.size.height)));
    }
    UIGraphicsBeginImageContextWithOptions(self.wkWebView.scrollView.contentSize, true, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);

    [self drawImagePageIndex:0 maxIndex:pageNum complet:^(BOOL complet) {
        if (complet) {
            UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            self.wkWebView.scrollView.contentOffset = originalOffset;
            if (image != nil) {
                //保存图片到相册
                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
            }
        }
    }];
- (void)drawImagePageIndex:(NSInteger)index maxIndex:(NSInteger)maxIndex complet:(void (^)(BOOL complet))block
{
    [self.wkWebView.scrollView setContentOffset:CGPointMake(0, (CGFloat)index * self.wkWebView.bounds.size.height) animated:YES];
    CGRect pageFrame = CGRectMake(0, (CGFloat)index * self.wkWebView.bounds.size.height, self.wkWebView.bounds.size.width, self.wkWebView.bounds.size.height);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self.wkWebView drawViewHierarchyInRect:pageFrame afterScreenUpdates:YES];
        if (index < maxIndex) {
            [self drawImagePageIndex:index + 1 maxIndex:maxIndex complet:block];
        } else {
            block(YES);
        }
    });
}
方案4:
    if (@available(iOS 11.0, *)) {
        WKSnapshotConfiguration *confige = [WKSnapshotConfiguration new];
        confige.rect = CGRectMake(0, 0, self.wkWebView.scrollView.contentSize.width, self.wkWebView.scrollView.contentSize.height);
        confige.snapshotWidth = [NSNumber numberWithFloat:self.wkWebView.scrollView.contentSize.width / [UIScreen mainScreen].scale];
        [self.wkWebView takeSnapshotWithConfiguration:confige completionHandler:^(UIImage *_Nullable snapshotImage, NSError *_Nullable error) {
            if (snapshotImage != nil) {
                //保存图片到相册
                UIImageWriteToSavedPhotosAlbum(snapshotImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
            }
        }];
    } else {
        // Fallback on earlier versions
    }
    
    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (image) {
        NSString *msg = nil;
        if (error != NULL) {
            msg = @"保存图片失败";
        } else {
            msg = @"保存图片成功,可到相册查看";
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"信息提示"
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

用到的类的代码如下

@interface ZYCaptureScreenShotView : UIPrintPageRenderer
-(instancetype)initWithFormatter:(UIPrintFormatter*)formatter andContentSize:(CGSize)contentSize;
-(UIImage*)getContentImage;
@end
@interface ZYCaptureScreenShotView ()
@property (nonatomic, strong)  UIPrintFormatter *formatter;
@property (nonatomic, assign) CGSize contentSize;
@end
@implementation ZYCaptureScreenShotView

- (instancetype)initWithFormatter:(UIPrintFormatter *)formatter andContentSize:(CGSize)contentSize
{
    if (self = [super init]) {
        self.formatter = formatter;
        self.contentSize = contentSize;
        [self addPrintFormatter:formatter startingAtPageAtIndex:0];
    }
    return self;
}

- (CGRect)paperRect
{
    return CGRectMake(0, 0, self.contentSize.width, self.contentSize.height);
}

- (CGRect)printableRect
{
    return CGRectMake(0, 0, self.contentSize.width, self.contentSize.height);
}

- (CGPDFPageRef)printContentToPDF
{
    NSMutableData *data = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(data, self.paperRect, nil);
    [self prepareForDrawingPages:NSMakeRange(0, 1)];
    CGRect bounds = UIGraphicsGetPDFContextBounds();
    UIGraphicsBeginPDFPage();
    [self drawContentForPageAtIndex:0 inRect:bounds];
    UIGraphicsEndPDFContext();
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(CFBridgingRetain(data));
    CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(provider);
    return CGPDFDocumentGetPage(document, 1);
}

- (UIImage *)convertPDFPageToImage:(CGPDFPageRef)pdfPage
{
    CGRect pageRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFTrimBox);

    CGSize contentSize = CGSizeMake(floor(pageRect.size.width), floor(pageRect.size.height));

    UIGraphicsBeginImageContextWithOptions(contentSize, true, 2.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);

    CGContextFillRect(context, pageRect);

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0, contentSize.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetInterpolationQuality(context, kCGInterpolationLow);
    CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
    CGContextDrawPDFPage(context, pdfPage);
    CGContextRestoreGState(context);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)getContentImage
{
    UIImage *image;
    if ([self printContentToPDF]) {
        image = [self convertPDFPageToImage:[self printContentToPDF]];
    }
    return image;
}
@end

@interface WKWebView (ZYToFile)
- (UIImage *)imageRepresentation;
- (NSData *)PDFData;
@end
#import 

@implementation WKWebView (ZYToFile)

- (UIImage *)imageRepresentation{
    CGFloat scale = [UIScreen mainScreen].scale;
    
    CGSize boundsSize = self.bounds.size;
    CGFloat boundsWidth = boundsSize.width;
    CGFloat boundsHeight = boundsSize.height;
    
    CGSize contentSize = self.scrollView.contentSize;
    CGFloat contentHeight = contentSize.height;
    
    CGPoint offset = self.scrollView.contentOffset;
    
    [self.scrollView setContentOffset:CGPointMake(0, 0)];
    
    NSMutableArray *images = [NSMutableArray array];
    while (contentHeight > 0) {
        UIGraphicsBeginImageContextWithOptions(boundsSize, NO, 0.0);
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [images addObject:image];
        
        CGFloat offsetY = self.scrollView.contentOffset.y;
        [self.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];
        contentHeight -= boundsHeight;
    }
    
    [self.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)];
    }];
    UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return fullImage;
}

- (NSData *)PDFData{
    UIViewPrintFormatter *fmt = [self viewPrintFormatter];
    UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
    [render addPrintFormatter:fmt startingAtPageAtIndex:0];
    CGRect page;
    page.origin.x=0;
    page.origin.y=0;
    page.size.width=600;
    page.size.height=768;
    
    CGRect printable=CGRectInset( page, 50, 50 );
    [render setValue:[NSValue valueWithCGRect:page] forKey:@"paperRect"];
    [render setValue:[NSValue valueWithCGRect:printable] forKey:@"printableRect"];
    
    NSMutableData * pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );
    
    for (NSInteger i=0; i < [render numberOfPages]; i++)
    {
        UIGraphicsBeginPDFPage();
        CGRect bounds = UIGraphicsGetPDFContextBounds();
        [render drawPageAtIndex:i inRect:bounds];
        
    }
    UIGraphicsEndPDFContext();
    return pdfData;
}
@end

总结

经过多次测试,只有方案4最靠谱,能截到完整的长图。前三个都有问题,以上方案大部分来自互联网。

你可能感兴趣的:(Webview保存长图)