Android WebView or ImageView?

2019-02-19 07:31发布

问题:

I have an App that downloads and displays images from URL's. This works fine using

URLConnection conn = urls[i].openConnection();
conn.connect();
if(conn.getContentLength() > 0)
is = conn.getInputStream();
bis = new BufferedInputStream(is);
Bitmap temp = BitmapFactory.decodeStream(bis);

I noticed that WebView's download and display images much faster then the above code so I thought i would try.

String url = "http:\\image.jpg"
int mWidth = getSystemService(Context.WINDOW_SERVICE).getDefaultDisplay().getWidth()
webView.loadData("<html><body> <img src=\"" + url + "\" width=\"" + mWidth + "px\" height=\"auto\"></body></html>", "text/html", null);

Although this gets the image much faster it does not scale the image to the size of the screen, the large images always go beyond the WebView's width and require scrolling to view properly.

Does anyone know how i can fix the issue to display the image properly in the WebView or how to speed up the download of the image in the first place?

I would prefer to have the download speeded up, but i am happy to use the WebView if i can scale the image correctly.

回答1:

Set the image elements width to 100% via CSS, height should scale according to the aspect/ratio of the image.



回答2:

I have not tried this yet. But from your question i can see that the only probelm you face using webview is the screen size fit problem. To overcome this, you can simply set the initial scale level to 1 and your Image should fit inside of the screen.

Try this,

     <WebView  
      android:id="@+id/webview"
      android:layout_width="50dip" 
      android:layout_height="50dip"/>

webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);

NOTE: i am not sure how far this will be effective. I haven't tried this yet. But giving a try is worth it.