在WebView中将图像适应屏幕

9
在我的应用中,我使用 webView 来显示图片。所以对于每个图片,我都会创建一个小的 HTML 代码来加载到 webView 中。因此,我的 HTML 代码基本上只包含一个 img 标签(带有我的图片路径)。
我的图片有不同的尺寸,这就是为什么我想将 webView 缩放以适应图片宽度和 webView 宽度之间的比例,这样用户就不必缩放才能看到整张图片。
是否有一种方法实现这个功能?
谢谢。
7个回答

4
如果你正在创建HTML代码(你说你是),那么你可以偷懒:
在HTML代码中:
img src="xxx" width="100% >

3

对我来说,那个方法很管用:

webView.setInitialScale(30);
WebSettings webSettings = webView.getSettings();
webSettings.setUseWideViewPort(true);

谢谢你的回答。如果我使用这个,现在我的大图片(约1000像素*2000像素)将居中对齐,但我的小图片(宽度为320像素)会变得非常小,我必须放大才能看到它们。 - Trox

2
我为您提供的解决方法是:我阅读了一些资料,发现为了适应屏幕宽度,您需要在HTML或XML文件中的标签内添加以下代码:
width="100%"

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

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
你可以在网页中使用一些 jQuery 来完成它。
类似这样:
$(document).ready(function(){
   var windowWidth = $(window).width()+"px";
   $("#imagID").width(windowWidth);
});

1

我找到了一个解决方案。使用这个计算:

device-width * (152 / density)

使用displayMetrics.widthPixelsdisplayMetrics.densityDpi检索设备宽度和密度

在img标签中设置计算为宽度

值152最初是160,但当使用160时,图像看起来比屏幕大。

结果是,图像最初适合屏幕,并且缩放正常工作。


1

你不直接使用一些JavaScript将图像传入Android应用并在自定义对话框中显示这些图像,从而根据内容缩放对话框,有什么原因吗?

就个人而言,我认为这种解决方案比你的方法更加优雅。


0

你为什么要使用 WebView 来完成这个任务呢?如果使用 ImageView,你可以将 scaleType 设置为适应 ImageView 大小的方式来显示图片。


8
由于内置的缩放和水平/垂直滚动功能,因此如此。 - Trox
或者一个带有ImageView的对话框?这太疯狂了吧!谁会这样做。 - JoxTraex

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