Android WebView,将图像缩放以适应屏幕

53

我现有的: 我正在从URL加载图像。我只需执行 (WebView).loadUrl(imageurl, extraheaders)

我的问题: 图片未能在 WebView 中全宽显示,四周留有空白(就像在桌面浏览器中打开小图片一样)

我尝试过的: 将 LayoutAlgorithm 设置为 SINGLE_COLUMN,可以完美解决,但缩放功能无效(我已在 WebView.getSettings() 中启用了它,不知道为什么)。将 setUseWideViewPort(true); 设为 true 可以让图像不留任何空白,但同时也会完全缩放。


最好不要使用LayoutAlgorithm.SINGLE_COLUMN,因为它已经被弃用,现在已经过时了。 - Sarim Sidd
11个回答

100

你也可以像这样做。

在你的数据字符串开头添加 CSS 样式以针对 img(取决于你的网页数据格式)。

<style>img{display: inline; height: auto; max-width: 100%;}</style>

为了快速在 WebView 中对数据进行处理,我这样做。

WebView content = (WebView) findViewById(R.id.webView1);
content.loadDataWithBaseURL(null, "<style>img{display: inline;height: auto;max-width: 100%;}</style>" + post.getContent(), "text/html", "UTF-8", null);

就像bansal21ankit所说的那样,但不需要额外的工作,它将在您HTML中的每个图像上工作。


编辑(有关帖子内容的澄清):

您可以使用示例中的post.getContent()之外的任何text/html值。

此处的帖子内容只是一个text/html内容的示例,该内容从某个数据源加载,然后与style部分连接,使给定内容中的任何图像适合屏幕。


@Tony...你能解释一下你帖子中的post_content部分吗?我该如何通过URL获取它?谢谢! - Johnny Wu
@JohnnyWu 更新了答案,并提供了关于 post.getContent() 部分的信息。 - Tony
1
我有一张带数据的图片,但它不起作用 :( - Amin Pinjari
它完美地运行了 ❤️ - mustafiz012
它完美地运作了 ❤️ - mustafiz012
显示剩余2条评论

60

我也遇到了同样的问题,而这样做可以很好地解决:

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();

String data = "<html><head><title>Example</title><meta name=\"viewport\"\"content=\"width="+width+", initial-scale=0.65 \" /></head>";
data = data + "<body><center><img width=\""+width+"\" src=\""+url+"\" /></center></body></html>";
webView.loadData(data, "text/html", null);

编辑: 由于这仍然是被接受的答案,这里提供更好的解决方案(所有功劳归功于下面的Tony):


WebView content = (WebView) findViewById(R.id.webView1);
content.loadDataWithBaseURL(null, "<style>img{display: inline;height: auto;max-width: 100%;}</style>" + post.getContent(), "text/html", "UTF-8", null);

1
谢谢,使用这个结构体是否有办法发送额外的头部信息,比如referer? - artouiros
2
请查看下面的Tony答案,那是适用于各种平台和设备的解决方案。 - 2cupsOfTech
在我的情况下,当加载带有图像的HTML数据时,如果不像上面那样强制设置样式,则会导致无限滚动(Webview 尝试调整高度而没有边缘),从而在 Android 9 及以上版本中发生崩溃。loadDataWithBaseUrl + <style>img .... 解决了我的问题,谢谢。 - mochadwi

45

你应该将webView缩放以适应屏幕:

 WebView data = (WebView) getViewById(R.id.webview1);
 data.getSettings().setLoadWithOverviewMode(true);
 data.getSettings().setUseWideViewPort(true);

9
如果图像尺寸大于屏幕,它不会使图像适应屏幕,而是让屏幕适应图像(看起来就像有人缩小视角以查看整个内容)。 - supermus
2
@supermus 当LoadWithOverviewMode和UseWideViewPort都启用时,图像将适合屏幕。我开发的API级别为16,你的说法在这个版本上不正确。我点赞这个答案。 - 3k-
不是完全一样的问题,但这对我有用,我在加载到 webview 的 html 文件中使用了图像。<html> <body > <img src="restaurantes.png" style="display: inline; height: auto; max-width: 100%;"> </body> </html> webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setSaveFormData(true); webView.getSettings().setBuiltInZoomControls(true); webView.loadUrl("file:///android_asset/your_file.html"); - magorich

10

有点晚了,但我希望这会有所帮助,你可以做以下几件事:

String html = "<html><body><img src=\"" + URL + "\" width=\"100%\" height=\"100%\"\"/></body></html>";
mWebView.loadData(html, "text/html", null);

这将使图像与您的 WebView 的宽度完全相同,其余部分您可以调整 WebView 本身。


1
这可能有点晚了,但是使用这种方法缩放控件不起作用。但它很酷很迷人 :) - Farhad

9

代码:

web = (WebView) findViewById(R.id.at_image_web);
web.getSettings().setBuiltInZoomControls(true);
web.getSettings().setUseWideViewPort(true);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setLoadWithOverviewMode(true);
web.loadUrl(linkImage);

9
我的建议是:我看到一个方法可以让网页宽度适应屏幕大小,只需要在HTML或XML的标签内添加以下代码即可:
width="100%"

所以我所做的是,而不是缩放和缩小图像,我获取了xml,将其放入StringBuilder中,找到位于<img>字段内的src="https://blablabla.com/image.png",并在"src"子字符串之前插入"width="100%"",然后使用StringBuilder设置我的webView,我的代码如下:

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);
}

希望这能帮到你,我花了几个小时才弄清如何解决这个问题。


1
这对我有用:
``` webView = (WebView) findViewById(R.id.webView); WebSettings webSettings = webView.getSettings(); webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); ```

0

我认为这将解决你的问题:

      WebView web;

      web = (WebView) findViewById(R.id.webkit);
      web.setWebViewClient(new Callback());
      web.getSettings().setJavaScriptEnabled(true);
      web.getSettings().setLoadWithOverviewMode(true);
      web.getSettings().setUseWideViewPort(true);
      web.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
      web.setScrollbarFadingEnabled(false);

2
这不是滚动条的问题,我的空白空间大约占据了屏幕的50%。仍然一样。就像图像被缩小了更多,超出了屏幕尺寸。 - artouiros

0
这段代码对我有效:
String strData = "<head>" + "<style>" + ".smal-video-pnl,.smal-video-thumb,.detail-hldr{margin-left: 0px;margin-right:0px;}" + "</style>" +
            "</head>" + mListItem.get(position).getTitbits();
holder.webViewStatus.loadDataWithBaseURL(null, strData, "text/html", "UTF-8", null);

0

我注意到如果我们使用这个CSS,图片会适应屏幕宽度,但高度保持不变,这看起来像是从侧面压缩了图片。

<style>img{display: inline; height: auto; max-width: 100%;}</style>

所以为了避免这种情况,我只在这段代码中做了一个简单的更改。只需先将宽度设置为100%,然后再将高度设置为自动即可。这对我来说完美地起作用了。

<style>img{display: inline; max-width: 100%; height: auto;}</style>

顺便说一下,感谢Tony提供的优美解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接