混合开发H5的图片怎么适配自己想要的大小

1.先上个自己没适配的图,这个图没显示全,因为用的是webview 所以 用的是webView的代理事件 解决

2.上代码

NSString *injectionJSString =

     @"var script = document.createElement('script');"

     "script.type = 'text/javascript';"

    "script.text = "function ResizeImages() { "

    "var myimg,oldwidth;"

    "var maxwidth=375;" // UIWebView中显示的图片最大宽度

    "for(i=0;i <document.images.length;i++){"

    "myimg = document.images[i];"

    "oldwidth = myimg.width;"

    "if(oldwidth > maxwidth){"//原图大于最大宽度

            "if(myimg.width>myimg.height){"//原图的宽度大于高度

    

    "myimg.width=maxwidth*2/3;"

            "myimg.height = myimg.width*myimg.height/oldwidth;" //修改高度

            "}else{"//原图的宽度小于高度

    "myimg.width=maxwidth*2/3;"

    "myimg.height = myimg.width*myimg.height/oldwidth;" //修改高度

               "}"

            "}"

    

        "}"

    "}";"

    

    "document.getElementsByTagName('head')[0].appendChild(script);";

    

    [webView stringByEvaluatingJavaScriptFromString:injectionJSString];

       [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];

 3.然后出的效果图是这样的

4.既然写到这里了,我就顺便把计算webView的内容高度也写了吧

5.上代码

 NSString *injectionJSString2 = @"var script = document.createElement('meta');"

    "script.name = 'viewport';"

    "script.content="initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no";"

    "document.getElementsByTagName('head')[0].appendChild(script);";

    

    [webView stringByEvaluatingJavaScriptFromString:injectionJSString2];

    

    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"];//修改百分

    CGRect frame = webView.frame;

    frame.size.width = SKDeviceWidth;

    frame.size.height = 1;

    webView.frame = frame;

    if (FourInch) {

                  frame.size.height = webView.scrollView.contentSize.height+25;

    }else if (FourOfSevenInch )

    {

                  frame.size.height = webView.scrollView.contentSize.height+15;

    

    }else if (FiveOfFifthInch)

    {

              frame.size.height = webView.scrollView.contentSize.height+15;

    }

    

 6.其实方法有很多,不管是上面的适配还是得到高度,还可以用另外一种方法统一解决

7.这个 我就只上一个关键代码 

    //获取webView 中的所有H5内容

       NSString *str=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];

这个数据获得,能得到所有H5代码的标签,内容,等等 通过这个 可以自己拿到字符去改变,嘿嘿 这个我没做,不过可以走通

原文地址:https://www.cnblogs.com/pp-pping/p/5979906.html