美文网首页
WKWebView加载html图片过大

WKWebView加载html图片过大

作者: 乂滥好人 | 来源:发表于2020-06-02 14:53 被阅读0次

    WKWebView加载html图片过大,将图片缩放适配屏幕方法

        NSString *str = @"var script = document.createElement('script');"
        "script.type = 'text/javascript';"
        "script.text = \"function ResizeImages() { "
        "var myimg,oldwidth;"
        "var maxwidth=300;" //缩放系数  改变参数控制图片缩放大小
        "for(i=0;i <document.images.length;i++){"
        "myimg = document.images[i];"
        "if(myimg.width > maxwidth){"
        "oldwidth = myimg.width;"
        "myimg.width = maxwidth;"
        "myimg.height = myimg.height * (maxwidth/oldwidth);"
        "}"
        "}"
        "}\";"
        "document.getElementsByTagName('head')[0].appendChild(script);";
        [_webView evaluateJavaScript:str completionHandler:nil];
        [_webView evaluateJavaScript:@"ResizeImages()" completionHandler:nil];
    
    - (WKWebView *)webView {
      if (!_webView) {
        _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavHeighe, SCREEN_W, SCREEN_H-kNavHeighe - kSafeBottomAreaH)];
        NSString *str = @"var script = document.createElement('script');"
        "script.type = 'text/javascript';"
        "script.text = \"function ResizeImages() { "
        "var myimg,oldwidth;"
        "var maxwidth=300;" //缩放系数  改变参数控制图片缩放大小
        "for(i=0;i <document.images.length;i++){"
        "myimg = document.images[i];"
        "if(myimg.width > maxwidth){"
        "oldwidth = myimg.width;"
        "myimg.width = maxwidth;"
        "myimg.height = myimg.height * (maxwidth/oldwidth);"
        "}"
        "}"
        "}\";"
        "document.getElementsByTagName('head')[0].appendChild(script);";
        [_webView evaluateJavaScript:str completionHandler:nil];
        [_webView evaluateJavaScript:@"ResizeImages()" completionHandler:nil];
        NSString *strsss = [NSString stringWithFormat:@"%@%ld", JS_Details_URL, (long)self.newId];
        NSURL *url = [NSURL URLWithString:strsss];
        NSURLRequest *httpRequest = [NSURLRequest requestWithURL:url];
        [_webView loadRequest:httpRequest];
        _webView.scrollView.delegate = self;
        _webView.navigationDelegate = self;
      }
      return _webView;
    }
    
    
    

    相关文章

      网友评论

          本文标题:WKWebView加载html图片过大

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