WebView: Maintain Background Image Aspect

Viewed 49

I have a WebView app that is used to load a remote web page. I have set a background image to be displayed before the web page is fully loaded.

activity_main.xml:

...
<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/clientWebView"
    android:background="@drawable/splash"
...

MyClient.java:

...
WebView clientView = (WebView) mainActivity.findViewById(R.id.clientWebView);
clientView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
WebSettings viewSettings = clientView.getSettings();
viewSettings.setJavaScriptEnabled(true);
viewSettings.setLoadWithOverviewMode(true);
viewSettings.setUseWideViewPort(true);
...

The issue is that the background image is stretched/squished, especially in portrait mode. I have been looking for an answer on StackOverflow & Google but have not come across anything that works.

1 Answers

Yes, background of any view will always fit to the screen dimensions.

Which will cause the image to stretch out.

Best thing is you need to add an ImageView behind the WebView and set image as its src

Then,

Add the following line to your ImageView

android:scaleType="centerCrop"

This ensures that your Image does not stretch out

Related