适应webview的图片大小

10

我打算在Webview中显示来自SD卡的图片,以利用Webview内置的缩放功能。但是,我遇到了一个问题:显示比屏幕尺寸大的图像(例如1800x1200)以适应屏幕最初的大小,就像在ImageView中一样。我希望图片一开始就能完整地显示,并为用户提供缩放控制。

我已经尝试使用WRAP_CONTENT设置Webview的宽度和高度,但这并没有起作用。有什么想法吗?以下是我正在使用的代码片段:

    String path = getRealPathFromURI(mUriList.get(0)); // this gets the file path
    webView = (WebView) findViewById(R.id.WebView01);
 WebSettings settings= webView.getSettings();
 settings.setBuiltInZoomControls(true);
 settings.setSupportZoom(true);     
 webView.loadUrl("file://" + path);

可能是Can Android's WebView automatically resize huge images?的重复问题。 - Dan Dascalescu
4个回答

9
 private WebView mWebView2;
    mWebView2 = (WebView)findViewById(R.id.webview);
    mWebView2.getSettings().setJavaScriptEnabled(true);
    mWebView2.getSettings().setLoadWithOverviewMode(true);
    mWebView2.getSettings().setUseWideViewPort(true);
    mWebView2.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    mWebView2.setScrollbarFadingEnabled(true);
    mWebView2.loadDataWithBaseURL("file:///android_asset/", "<img src=\"banner5.png\" height=\"98%\" width=\"100%\"/>", "text/html", "utf-8", null);

图片在资产文件夹中


5
如果你正确编写HTML,就不需要进行任何“setLoadWithOverviewMode”、“setUseWideViewPort”或“setInitialScale”的操作,并且绝对没有理由启用JavaScript。
这一行代码对我有效:
webView.loadDataWithBaseURL("file://" + directory, "<img src=\"" + name + "\" width=\"100%\"/>", "text/html", "utf-8", null);
下划线的HTML代码是:
<img src=YourImage.png width="100%" />,不设置高度,则其宽高比将保持不变。

不设置高度(或将其覆盖为“auto”)对我也起作用。参见链接:https://github.com/FezVrasta/bootstrap-material-design/issues/768 - Dan Dascalescu

3

这对我很有帮助:

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

0
WebSettings settings = webView.getSettings();

settings.setUseWideViewPort(true);

settings.setLoadWithOverviewMode(true)

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