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

iam小码哥| 阅读:150 发表时间:2017-07-27 10:18:18 ios
摘要:在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;

本文为iam小码哥原创,转载请注明出处!
如果您觉得好,可以打赏作者:

已有0条评论

昵称:
邮箱:

  • 最新评论

若兰网 - www.rolan.wang
反馈
微信订阅号