Fitting Image on Android WebView Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Fitting Image on Android WebView without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m using WebView and i want to display an image inside it.

I want to fit the image in webview. (The image becomes so big so i have to scroll horizontally)

I show images like this (if it matters): <img src="path" alt="">

What i have tried:

WebView content = (WebView) findViewById(R.id.webView1);
content.loadDataWithBaseURL(null, "<style>img{display: inline;height: auto;max-width: 100%;} 
</style>" + CONTENT, "text/html", "UTF-8", null);

But when i use this method, the images are not visible. Only texts

Also i tried this:

   WebSettings settings = preview.getSettings();
   settings.setLoadWithOverviewMode(true);
   settings.setBuiltInZoomControls(true);

It works but it’s not good since it zoom out the webview and the texts become unreadable. Is there any other way?

Answer

if you use this code it will allow you to fit all the image in the webview

String imageUrl = "<Put here the image>";
        String html = "<html><head>" +
                "<meta name="viewport" content="width=device-width, user-scalable=no">"+
                "<style>n" +
                "html,body{ margin:auto;}"+
                "#image{n" +
                "    width: 100vw;n" +
                "    height: 100vh;n" +
                "}n" +
                "</style></head>n" +
                "<body>n" +
                "<img id="image" src=""+imageUrl+"" alt ="no image">n" +
                "</body></html>";
        webView.loadDataWithBaseURL(null,html,"text/html", "UTF-8", null);
We are here to answer your question about Fitting Image on Android WebView - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji