在我的应用程序,我显示图片感谢webView。 因此,对于每个图像,我创build了一个我用webView加载的小型HTML代码。 所以我的HTML代码基本上包含在一个img标签(与我的照片的path)。
我的图片有不同的大小,这就是为什么我想设置我的webView缩放,以适应图片宽度的webView宽度。 所以用户不必放大或缩小就可以看到整个图像。
有没有办法实现它?
谢谢。
如果你正在创buildHTML代码(你说你是),你可以作弊:
在html代码中:
img src="xxx" width="100% >
那为我做了诡计:
webView.setInitialScale(30); WebSettings webSettings = webView.getSettings(); webSettings.setUseWideViewPort(true);
我的工作是这样的:我读到,为了适应屏幕的宽度,你应该把这个添加到你的HTML或XML内的字段:
width="100%"
所以我做的是,而不是缩放和缩放图像,我得到的XML,把它放在一个StringBuilder,findsrc =“http://img.androidcookie.com/android/image.png”是在场内和之前“src”子串我插入了“width =”100%“”,然后y用StringBuilder设置我的webView,mi代码是这样的:
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); }
希望这有助于,我花了几个小时才弄清楚如何解决这个问题。
我find了一个解决scheme。
使用这个计算。
设备宽度*(152 /密度)
使用displayMetrics.widthPixels和displayMetrics.densityDpi检索设备宽度和密度
设置为在img标签中的宽度
值152本来是160,但是当使用160时,看起来像Image比屏幕大。
结果是,图像最初适合屏幕和,放大工作正常。
是不是有一个原因,你不只是使用一些JavaScript传递到android应用程序的图像,并调出一个自定义对话框中的图像,使其根据内容的比例。
就我个人而言,我认为这个解决scheme对您的方法更为优雅。
你可以在网页中使用一个小的jQuery来完成它。
就像是:
$(document).ready(function(){ var windowWidth = $(window).width()+"px"; $("#imagID").width(windowWidth); });
是否有一个原因,你正在使用WebView来完成这个? 使用ImageView,您可以设置scaleType以使图像适合ImageView的大小。