iOS中UIWebView加载html 图片大小自适应的方法

摘要:在UIWebView中,我们可能会碰到由于UIWebView显示的图片太大,而导致图片显示不全,影响体验性,我在开发中总结了一下几种方法;

方法一:

NSString *htmls = [NSString stringWithFormat:@"<html> /n"
                           "<head> /n"
                           "<style type=/"text/css/"> /n"
                           "body {font-size:15px;}/n"
                           "</style> /n"
                           "</head> /n"
                           "<body>"
                           "<script type='text/javascript'>"
                           "window.onload = function(){/n"
                           "var $img = document.getElementsByTagName('img');/n"
                           "for(var p in  $img){/n"
                              " $img[p].style.width = '100%%';/n"
                               "$img[p].style.height ='auto'/n"
                           "}/n"
                           "}"
                           "</script>%@"
                           "</body>"
                           "</html>",htmlString];
 [self.webView loadHTMLString:htmlString baseURL:nil];

方法二:

 [webView stringByEvaluatingJavaScriptFromString:
     @"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 stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];

方法三:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
  NSString *js = @"function imgAutoFit() { /
     var imgs = document.getElementsByTagName('img'); /
     for (var i = 0; i < imgs.length; ++i) {/
        var img = imgs[i];   /
        img.style.maxWidth = %f;   /
     } /
  }";
  js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
  
  [webView stringByEvaluatingJavaScriptFromString:js];
  [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
}

方法四:

    将scalesPageToFit属性设置为YES

 

  mywebView.scalesPageToFit = YES;

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/98549.html

(0)
上一篇 2021年8月21日
下一篇 2021年8月21日

相关推荐

发表回复

登录后才能评论