Android WebView, Scaling Image to fit the screen

前端 未结 9 1146
醉梦人生
醉梦人生 2020-11-29 01:13

What I have: I\'m loading image from a URL. I simply do (WebView).loadUrl(imageurl, extraheaders)

What I get: Image i

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 02:11

    What worked for me was this: I read that in order to fit the width of the screen you should add this to your HTML or xml inside the field:

    width="100%"
    

    So what I did was, instead of scaling and zooming the images, I got the xml, put it in a StringBuilder, found the src="https://blablabla.com/image.png" that is inside the field and just before the "src" substring I inserted the "width="100%"", then y set my webView with the StringBuilder, mi code is this:

    public void setWebViewWithImageFit(String content){
    
            // content is the content of the HTML or XML.
            String stringToAdd = "width=\"100%\" ";
    
            // Create a StringBuilder to insert string in the middle of content.
            StringBuilder sb = new StringBuilder(content);
    
            int i = 0;
            int cont = 0;
    
            // Check for the "src" substring, if it exists, take the index where 
            // it appears and insert the stringToAdd there, then increment a counter
            // because the string gets altered and you should sum the length of the inserted substring
            while(i != -1){
                i = content.indexOf("src", i + 1);
                if(i != -1) sb.insert(i + (cont * stringToAdd.length()), stringToAdd );
                ++cont;
            }
    
            // Set the webView with the StringBuilder: sb.toString()
            WebView detailWebView = (WebView) findViewById(R.id.web_view);
            detailWebView.loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);
    }
    

    Hope this helps, it took me some hours to figure out how to solve this.

提交回复
热议问题