I think I found a solution for most situations like this, as long as we just want to load a single image. It's kind of a workaround, and loses some image details as it resizes the image. Nevertheless it should work on most if not all devices out there.
I followed the approach to embed the image into a basic HTML page, and filled the <img>
tag with the width of the screen in pixels. For simplicity I skipped loading the HTML from a file and just generated it inside my Java code:
private String generatePage() {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int displayWidth = display.getWidth();
String result =
"<html>"
+ "<meta name=\"viewport\" content=\"target-densitydpi=device-dpi,width=device-width\">"
+ "<head>"
+ " <title>Title</title>"
+ "</head>"
+ "<body>"
+ "<image id=\"myImage\" src=\"drawable/image.jpg\" width=\"" + displayWidth + "px\" />"
+ "</body>"
+ "</html>";
return result;
}
I added this method to my Activity and used it to generate the code matching the device it runs on. The onCreate()
method now can be pretty straightforward:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual);
WebView webView = (WebView)findViewById(R.id.webView);
webView.loadDataWithBaseURL("file:///android_res/", generatePage(), "text/html", "utf-8", null);
webView.getSettings().setBuiltInZoomControls(true);
}
Important note: There are two details that you need to keep in mind, or it won't work.
You need to use the method
webView.loadDataWithBaseURL(...)
, otherwise you can't access the local android ressources inside the HTML. This way thesrc
attribute couldn't point to your image file.You need the tag
<meta name="viewport" content="...">
inside your HTML code, and it has to includetarget-densitydpi=device-dpi
inside itscontent
attribute. Otherwise the size of the image may still not match your viewport.
Note: You also can specify a minimal-scale
inside the viewport
tag, and this really affected my webview. The bad thing: At least on my Galaxy S3 mini running Jelly Bean 4.1.2 a minimal-scale
of less than 1.0 had no effect.