Search code examples
android-webviewxamarin.android

WebView: load images from resources (or assets)


I try to load images from resources (or assets):

String summary = "<html><body>Hello, images!" +
   "<br/>res: <img src='file:///android_res/drawable/icon.png'/>" +
   "<br/>asset: <img src='file:///android_asset/Icon.png'/>" +
   "<br/>www: <img src='http://www.droiddraw.org/droidraw-small.png'></body></html>";
web_view.LoadData(summary, "text/html", null);

Resource and asset images are not displayed. What's wrong?


Solution

  • If you use the LoadDataWithBaseUrl method instead it should work:

    webView.LoadDataWithBaseURL(null, summary, "text/html", null, null);
    

    One way to simplify things is to also load the WebView from an HTML asset, which would allow you to just use relative paths for the images.

    webView.LoadUrl("file:///android_asset/summary.html");
    

    Also make sure to set the BuildAction on any asset file to AndroidAsset.