美文网首页
WKWebView 生成长截图

WKWebView 生成长截图

作者: 野咪咕 | 来源:发表于2021-11-01 11:47 被阅读0次

    写个类继承NSObject

    .h 文件

    #import <Foundation/Foundation.h>

    #import <UIKit/UIKit.h>

    @interface Util : NSObject

    typedef void(^CapSuccessBlock)(UIImage *image,UIImage * thumbImage);

    typedef void(^CapFailureBlock)(NSError *error);

    +(instancetype)shareUtil;

    /**

     截屏

     @param url 截屏的url

     @param successBlock 截屏成功的回调

     @param failureBlock 截屏失败的回调

     */

    -(void)capturePicShareWitchUrl:(NSString*)url

                           success:(CapSuccessBlock) successBlock

                           failure:(CapFailureBlock) failureBlock;


    @end


    .m 文件

    #import "Util.h"

    #define kWindowWidth        [UIScreen mainScreen].bounds.size.width

    #define kWindowHeight      [UIScreen mainScreen].bounds.size.height

    #define KeyWindow          [[UIApplication sharedApplication].delegate window]

    @interface Util ()<UIWebViewDelegate>

    {

        CapSuccessBlock _successBlock;//截屏成功的回调

        CapFailureBlock _failureBlock;//截屏失败的回调

    }

    @end

    @implementation Util

    static Util * util;

    +(instancetype)shareUtil

    {

        if (!util)

        {

            static dispatch_once_t onceToken;

            dispatch_once(&onceToken, ^{

                util = [[Util alloc] init];

            });

        }

        return util;

    }

    /** 截屏 */

    -(void)capturePicShareWitchUrl:(NSString*)url

                           success:(CapSuccessBlock) successBlock

                           failure:(CapFailureBlock) failureBlock;

    {

        _successBlock = successBlock;

        _failureBlock = failureBlock;

        UIWebView * webView = [[UIWebView alloc] initWithFrame:KeyWindow.bounds];

        webView.delegate = self;

        webView.hidden = YES;

        NSMutableURLRequest *re2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

        [webViewloadRequest:re2];

        [KeyWindow addSubview:webView];

    }

    #pragma UIWebViewDelegate

    -(void)webViewDidFinishLoad:(UIWebView *)webView

    {

        UIImage * image = [self screenShotWithScrollView:webView.scrollView withSize:CGSizeZero];

        UIImage * thumbImage = [self screenShotWithScrollView:webView.scrollView withSize:CGSizeMake(kWindowWidth, kWindowHeight)];

        

        if (_successBlock)

        {

            _successBlock(image,thumbImage);

        }

        

        webView.delegate = nil;

        [webViewremoveFromSuperview];

        webView =nil;

    }

    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

    {

        if (_failureBlock)

        {

            _failureBlock(error);

        }

    }

    //图片

    - (UIImage *)screenShotWithScrollView:(UIScrollView *)scrollView withSize:(CGSize)size

    {

        UIImage* image;

        

        UIGraphicsBeginImageContextWithOptions(size.width==0?scrollView.contentSize:size, NO, [UIScreen mainScreen].scale);

        {

            CGPoint savedContentOffset = scrollView.contentOffset;

            CGRect savedFrame = scrollView.frame;

            scrollView.contentOffset = CGPointZero;

            scrollView.frame = size.width==0? CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height):CGRectMake(0, 0, size.width, size.height);

            [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];

            image =UIGraphicsGetImageFromCurrentImageContext();

            scrollView.contentOffset = savedContentOffset;

            scrollView.frame = savedFrame;

        }

        UIGraphicsEndImageContext();

        

        if (image != nil)

        {

            return image;

        }

        return nil;

    }

    @end




    调用

    -(void)captureView:(UIBarButtonItem*)item

    {

        UIWindow *window = [UIApplication sharedApplication].keyWindow;

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];

        hud.animationType  =MBProgressHUDAnimationZoom;

        hud.mode              =MBProgressHUDModeText;

        hud.detailsLabel.text = @"正在生成截图";

        hud.detailsLabel.font = [UIFont systemFontOfSize:17.0];

        

        [[Util shareUtil] capturePicShareWitchUrl:KCapUrl success:^(UIImage *image, UIImage *thumbImage) {

        [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];

            UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"截图成功,是否保存到相册" preferredStyle:UIAlertControllerStyleAlert];

            

            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)

            {

                [self saveImageToPhotos: image];

                [self saveImageToPhotos: thumbImage];

                [self showPromptWithText:@"保存到相册成功" hideAfterdelay:1.5];

            }];

            

            UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                

            }];

            

            [alertVCaddAction:action1];

            [alertVCaddAction:action2];

            

            [self presentViewController:alertVC animated:YES completion:nil];

            

        }failure:^(NSError *error) {

            

        }];

        

        

    }

    - (MBProgressHUD *)showPromptWithText:(NSString *)text hideAfterdelay:(CGFloat)timeInterval

    {

        UIWindow *window = [UIApplication sharedApplication].keyWindow;

      

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];

        hud.animationType  =MBProgressHUDAnimationZoom;

        hud.mode              =MBProgressHUDModeText;

        hud.detailsLabel.text = text;

        hud.detailsLabel.font = [UIFont systemFontOfSize:17.0];

        hud.removeFromSuperViewOnHide = YES;

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [hudhideAnimated:YES];

        });

        return hud;

    }

    #pragma mark - 保存截图到相册

    - (void)saveImageToPhotos:(UIImage*)savedImage

    {

        

        dispatch_async(dispatch_get_main_queue(), ^{

            UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

        });

        

    }

    //回调方法

    - (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo

    {

        NSString *msg = nil ;

        if(error != NULL)

        {

            msg =@"保存图片失败" ;

        }else

        {

            msg =@"保存图片成功" ;

        }

        

        NSLog(@"%@",msg);

        

    }

    相关文章

      网友评论

          本文标题:WKWebView 生成长截图

          本文链接:https://www.haomeiwen.com/subject/szszaltx.html